The C# language provides a built-in class, Random
, for generating random numbers based on a seed value. By default, the Random
class uses a system clock to generate a seed value.
The Random
class provides the following methods to generate random numbers.
Next()
methodThis method generates a random positive number within the range -2,147,483,648 to 2,147,483,647.
Random random = new Random();int num = random.Next();
Let's see an example of the Next()
method in the code snippet below:
using System;class Example{static void Main(){// instantiate Random classRandom random = new Random();// generate a random numberint n = random.Next();// print the number of consoleConsole.WriteLine("Random number: {0}", n);}}
Inside the main()
function:
Random
class and create an object called random
.Next()
method.Next(int)
methodThis method generates a random number that is less than the specified integer. Here, the specified integer acts as the upper bound.
Random random = new Random();int num = random.Next(int);
Let's see an example of the Next(int)
method in the code snippet below:
using System;class Example{static void Main(){// instantiate Random classRandom random = new Random();// generate a random numberint n = random.Next(50);// print the number of consoleConsole.WriteLine("Random number: {0}", n);}}
Inside the main()
function:
Random
class and create an object called random
.Next(int)
method.Next(int, int)
methodThis method generates a random number within the specified range. Here, the first integer acts as the lower bound and the second integer acts as the upper bound.
Random random = new Random();int num = random.Next(int, int);
Let's see an example of the Next(int, int)
method in the code snippet below:
using System;class Example{static void Main(){// instantiate Random classRandom random = new Random();// generate a random numberint n = random.Next(20, 30);// print the number of consoleConsole.WriteLine("Random number: {0}", n);}}
Inside the main()
function:
Random
class and create an object called random
.Next(int, int)
method in the range (20, 30).NextDouble()
methodThis method generates a random floating number within the range (0.0, 1.0).
Random random = new Random();int num = random.NextDouble();
Let's see an example of the NextDouble()
method in the code snippet below:
using System;class Example{static void Main(){// instantiate Random classRandom random = new Random();// generate a random numberdouble n = random.NextDouble();// print the number of consoleConsole.WriteLine("Random number: {0}", n);}}
Inside the main()
function:
Random
class and create an object called random
.NextDouble()
method.