# Fundamentals of Programming: Randon number generation

 ← Built-in functions Random number generation Subroutines (functions and procedures) →

An essential part of most games is the ability to use random numbers. These might be used to randomly place gold coins on a map, or to calculate whether you hit a target with a rifle at some distance.

```Dim rndGen As New Random()
Dim randomNumber As Integer
randomNumber = rndGen.Next()
```

The above code will give you a random number between 1 and 2,147,483,647. You might well require a number that is a little smaller. To get a random number between two set numbers, in this case 5 and 10 you can use the following:

```randomNumber = rndGen.Next(5,10)
```

So how exactly can we use this? Take a look at the following game:

```Dim rndGen As New Random()
Dim randomNumber As Integer
Dim guess as Integer
randomNumber = rndGen.Next(1,100)
console.writeline("Please guess the random number between 1 and 100")
Do
if guess > randomNumber
console.writeline("Too High")
end if
if guess < randomNumber
console.writeline("Too Low")
end if
Loop While guess <> randomNumber
console.writeline("Well done, you took x guesses to find it!")
```

Adjust the code above to tell the user how many guesses they took to find the random number. HINT: you'll need a variable

```    Sub Main()
Dim rndGen As New Random()
Dim randomNumber As Integer
Dim guess As Integer
Dim count As Integer = 1
randomNumber = rndGen.Next(1, 100)

Console.WriteLine("Please guess the random number between 1 and 100")
Do
If guess > randomNumber Then
Console.WriteLine("Too High")
End If
If guess < randomNumber Then
Console.WriteLine("Too Low")
End If
If guess <> randomNumber Then
count = count + 1
End If
If guess = randomNumber Then
Console.WriteLine("Well done, you took " & count & " guesses to find it!")
End If

Loop
End Sub
```