C# Program to Generate Random Number Easily
Random and calling Next(), like Random rnd = new Random(); int number = rnd.Next();.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { Random rnd = new Random(); int randomNumber = rnd.Next(1, 101); // 1 to 100 Console.WriteLine("Random number between 1 and 100: " + randomNumber); } }
Dry Run
Let's trace generating a random number between 1 and 100 through the code.
Create Random object
Random rnd = new Random(); // rnd is ready to generate numbers
Generate random number
int randomNumber = rnd.Next(1, 101); // randomNumber gets a value like 57
Print the number
Console.WriteLine prints: Random number between 1 and 100: 57
| Step | Action | Value |
|---|---|---|
| 1 | Create Random object | rnd ready |
| 2 | Call rnd.Next(1, 101) | randomNumber = 57 |
| 3 | Print output | "Random number between 1 and 100: 57" |
Why This Works
Step 1: Create Random instance
The Random class provides methods to generate random numbers. Creating an instance prepares the generator.
Step 2: Generate number with Next()
Calling Next(min, max) returns a random integer from min (inclusive) to max (exclusive).
Step 3: Output the result
Printing the number shows the random value to the user or program.
Alternative Approaches
using System; class Program { static void Main() { Random rnd = new Random(); double randomDouble = rnd.NextDouble(); // 0.0 to 1.0 Console.WriteLine("Random decimal between 0 and 1: " + randomDouble); } }
using System; class Program { static void Main() { int randomNumber = Random.Shared.Next(1, 101); Console.WriteLine("Random number between 1 and 100: " + randomNumber); } }
Complexity: O(1) time, O(1) space
Time Complexity
Generating a random number is a constant time operation because it does not depend on input size.
Space Complexity
Only a small fixed amount of memory is used for the Random object and the generated number.
Which Approach is Fastest?
Using Random.Shared is fastest for multiple calls because it avoids creating new objects.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Random instance with Next() | O(1) | O(1) | Simple random integers |
| Random.NextDouble() | O(1) | O(1) | Random decimal numbers |
| Random.Shared | O(1) | O(1) | Multiple random calls with better performance |