AQA · GCSE · Computer Science · Higher
Generating a bounded random number in C#
Figure 3 shows an incomplete C# program for a number guessing game. Line numbers are included but are not part of the program.
| 1 | Random rGen = new Random(); |
| 2 | int randomNumber; |
| 3 | |
| 4 | Console.WriteLine("Enter a number"); |
| 5 | int userNumber = Convert.ToInt32(Console.ReadLine()); |
| 6 | while (userNumber < 1 || userNumber > 100) |
| 7 | { |
| 8 | Console.WriteLine("Invalid number"); |
| 9 | userNumber = Convert.ToInt32(Console.ReadLine()); |
| 10 | } |
| 11 | Console.WriteLine("Valid number entered"); |
| 12 | if (randomNumber == userNumber) |
| 13 | { |
| 14 | Console.WriteLine("Number guessed correctly"); |
| 15 | } |
The program should generate a random number between 1 and 100 (including 1 and 100). Write the C# code that should be used on line 3 in Figure 3 to generate that number and assign it to the appropriate variable. You must use rGen.Next(a, b).
Write your answer first. You can study the marking guidance whenever you need it.
Study the marking See what earns credit and compare it with a full-mark answer.
Marking points
- 1 Assigns the result to randomNumber.
- 2 Calls rGen.Next with lower bound 1 and exclusive upper bound 101.
Full-mark answer
randomNumber = rGen.Next(1, 101);
Why this answer loses marks
I used the stated random call with the inclusive maximum as its upper argument.
The call excludes its upper argument, so this would omit the top value in the required range.