6
0/2

The program should simulate rolling a 20-sided die by generating a random number between 1 and 20 (including 1 and 20).

Figure 1

1      Random randGen = new Random();
2      int diceRoll;
3
4      Console.WriteLine("Enter your prediction (1-20):");
5      int prediction = Convert.ToInt32(Console.ReadLine());
6      while (prediction < 1 || prediction > 20)
7      {
8          Console.WriteLine("Invalid prediction, choose 1 to 20");
9          prediction = Convert.ToInt32(Console.ReadLine());
10     }
11     Console.WriteLine("Rolling the 20-sided die...");
12     if (diceRoll == prediction)
13     {
14         Console.WriteLine("Excellent prediction! You guessed the roll!");
15     }

Write the C# code that should be used on line 3 in Figure 1 to:

  • generate a random number between 1 and 20 inclusive
  • assign this number to the appropriate variable from the program.

You must use randGen.Next(a, b) in your C# code.

Note: randGen.Next(a, b) generates a random integer in the range a to b starting at a but finishing one before b.

[2]

Random number generation in a programming language Questions

Practise AQA GCSE Computer Science Random number generation in a programming language with exam-style questions for GCSE Computer Science. 8 questions, matched to the AQA GCSE Computer Science (8525) specification and written in Paper 1 and Paper 2 style. Every question includes a full worked solution and mark scheme, so you can see where marks are awarded rather than just whether you got the answer right.

PreviousNext

Random number generation in a programming language Questions

  1. GCSE
  2. /Computer Science
  3. /Random number generation in a programming language