Skip to content

Course home

Random number generation in a programming language

Random number generation in a programming language

Easy
12345678
Question 6

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]
Markscheme

Random number generation in a programming language Questions

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

8 exam-style questions on AQA GCSE Computer Science Random number generation in a programming language. Each one has a worked solution and a mark scheme showing where the marks go.

Question bank