Random numbers in C#
Random numbers allow a part of your program to behave in different ways each they are run. It could be as simple as mimicking the roll of a dice as the example below demonstrates, or it could be a method for choosing a small subset or questions from a much larger set in a quiz program.
Randomizing random numbers
In computing terms, there is no such thing as a random number. Instead there are different methods for calculating a random like pattern of numbers which appear to us to be random because they work with very large numbers.
There has to be a way to start generating these random numbers, otherwise they would always come out in the same random order each time.
The random number generator is told to start from somewhere other than the beginning of the list of random numbers, and they do it based on the current date and time. This is how the results seem to be random.
Getting a random number
If you want to generate a random number between 1 and 6 to simulate the roll of a dice, you could write a piece of code as follows :
System.Random RandomNumber = new System.Random(); int DiceValue; DiceValue = RandomNumber.Next(1, 7);
Note that the upper limit has to be 6 + 1
Examples Using Random Numbers
using System;
public class MyApp
{
public static void Main()
{
System.Random RandomNumber = new System.Random();
int DiceValue;
//Generate a random number from 1 to 6
DiceValue = RandomNumber.Next(1, 7);
//Display the random number
Console.WriteLine(“Dice value : {0} “, DiceValue);
}
}
The following generates many random numbers and stores them in an array.
using System;
public class MyApp
{
public static void Main()
{
System.Random RandomNumber = new System.Random();
Int[] DiceValue = new int[10];
for (int I = 0; I < 10 ; i++)
{
//Generate a random number from 1 to 6
DiceValue[i] = RandomNumber.Next(1, 7);
//Display the random numbers
Console.WriteLine(“Dice value : {0} “, DiceValue[i]);
}
}
}