How to Generate Random Numbers with C
Generating random numbers is an important programming task for game development, data encryption, and many other software applications. In this article, you will see how to generate different types of random numbers in C#.
The Random class in C# contains various methods that can be used to generate different types of random numbers with C#. You will need to import the System namespace to use the Random class.
Let’s first see how to generate integers with the C# Random class.
Generating Integers
To generate integers, you can use the Next() method from the random class. If you do not pass any argument value to the Next() method, it will return a non-negative integer of the type Int32.
The following script generates 5 random integers of the type Int32.
class Program { static void Main(string[] args) { Random rand = new Random(); for (int i = 0; i < 5; i ++) { Console.WriteLine(rand.Next()); } Console.ReadKey(); } }
Here is the output of the above script:
If you want to generate random integers below a certain maximum threshold, you can pass the threshold value to the Next() method. For instance, the following script returns random integers between 0 and 50.
class Program { static void Main(string[] args) { Random rand = new Random(); for (int i = 0; i < 5; i ++) { Console.WriteLine(rand.Next(50)); } Console.ReadKey(); } }
Here is the output of the above script. You can see that all the integers values are below the integer value of 50 now.
Finally, you can also generate integers between a certain range of values. To do so, you need to pass a minimum and a maximum value to the Next() method. The following script returns 5 random values between 50 and 100.
using System; using System.Collections.Generic; namespace c_sharp_tutorials { class Program { static void Main(string[] args) { Random rand = new Random(); for (int i = 0; i < 5; i ++) { Console.WriteLine(rand.Next(50, 100)); } Console.ReadKey(); } } }
Output:
Generating Floating-Point Numbers
To generate floating-point numbers with C#, you can use the NextDouble() method. This method generates random numbers between 0.0 and 1. Here is an example.
The script below generates 5 random floating-point numbers between 0 and 1.
class Program { static void Main(string[] args) { Random rand = new Random(); for (int i = 0; i < 5; i ++) { Console.WriteLine(rand.NextDouble()); } Console.ReadKey(); } }
Here is the output of the above script:
You can also generate floating-point numbers greater than 1. For instance, to generate floating-point numbers between 0 and 10, you can simply multiply the result of the NextDouble() method by 10 as shown in the following script.
class Program { static void Main(string[] args) { Random rand = new Random(); for (int i = 0; i < 5; i++) { Console.WriteLine(10 * rand.NextDouble()); } Console.ReadKey(); } }
This time in the output, you will see 5 random floating-point numbers in the range 0 and 10.
Generating Strings
You can also generate random strings of any length. There is no specific function for that in the Random class, however, you can create an array of characters and then randomly pick a character from any index which is generated using the Next() method. Let’s see this with an example.
In the following script, you create a character array of all 26 capital and small English letters and digits from 0 to 9.
Next, you create an empty character array of length equal to the length of the string that you randomly want to generate. After that, you create a for loop that iterates for the length of the random string.
Inside the for loop you use the Next() method to pick an index that is less than the character array. The index is then passed to the chars array to select a random character.
class Program { static void Main(string[] args) { Random rand = new Random(); string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; char [] random_string = new char[10]; var random = new Random(); for (int i = 0; i < random_string.Length; i++) { random_string[i] = chars[random.Next(chars.Length)]; } Console.WriteLine(random_string); Console.ReadKey(); } }
Here is the output of the script above. You can see a random string of length 10. Note that this method of generating random strings is only recommended for light-weight random number generation and not for encryption purposes.
Randomly Selecting Items from a List
Finally, you can also select random items from a string using the Next() method from the random module. The idea is similar to generating random strings. You simply have to randomly select the index of a list, which can then be used to fetch an item randomly.
Here is an example.
class Program { static void Main(string[] args) { Random rand = new Random(); List<string> items = new List<string>(); items.Add("Red"); items.Add("Green"); items.Add("Blue"); items.Add("Yellow"); items.Add("Orange"); for (int i = 0; i < 2; i++) { Console.WriteLine(items[rand.Next(items.Count)]); } Console.ReadKey(); } }
The output of the above script:
Other useful articles:
- TOP-10 Basic C# Interview Questions and Answers
- TOP-10 C# Questions for Advanced Programmers
- 10 Important C# Interview Questions and Answers
- Most Asked C# Interview Q & A
- C# Interview for Beginners
- TOP-10 Advanced C# Interview Questions and Answers
- Introduction to Functions in C#
- C# Jagged Arrays
- C Sharp Interview Questions for 5 Years Experience
- C Sharp Interview Questions for Testers
- C Sharp Questions for 10 Years Experience
- Iteration Statements in C#
- Exception Handling in C#
- C Sharp Methods
- C# Data Types
- C# Vs. C++
- Regular Expressions in C Sharp
- Defining Nested Methods in C Sharp
- C Sharp Dynamic Data Type
- C Custom Exceptions
- How to Generate Random Numbers with C Sharp
- Pass by Value vs Pass by Reference in C Sharp