What is the Random Class?
The Random
class in C# generates pseudo-random numbers. It's useful for games, simulations, and testing.
Creating a Random Object
Random random = new Random();
// Or (commonly used name)
Random rnd = new Random();
Important: Create the Random object ONCE, not inside a loop!
❌ Wrong:
for (int i = 0; i < 10; i++)
{
Random rnd = new Random(); // BAD! Creates same seed
int iNumber = rnd.Next(1, 10);
}
✅ Correct:
Random rnd = new Random(); // Create once
for (int i = 0; i < 10; i++)
{
int iNumber = rnd.Next(1, 10); // Use multiple times
}
Generating Random Integers
Next() - Random Integer
Random rnd = new Random();
// Random non-negative integer
int iRandom = rnd.Next();
Console.WriteLine(iRandom); // e.g., 1847362947
Next(max) - Random Integer from 0 to max-1
Random rnd = new Random();
// Random number from 0 to 9
int iNumber = rnd.Next(10);
Console.WriteLine(iNumber); // 0, 1, 2, ..., 9
// Random number from 0 to 99
int iNumber2 = rnd.Next(100);
Console.WriteLine(iNumber2); // 0-99
Next(min, max) - Random Integer from min to max-1
Random rnd = new Random();
// Random number from 1 to 10
int iDiceRoll = rnd.Next(1, 11); // 1-10 inclusive
Console.WriteLine(iDiceRoll);
// Random number from 10 to 20
int iNumber = rnd.Next(10, 21); // 10-20 inclusive
Console.WriteLine(iNumber);
// Random number from 0 to 30 (from course)
int iRandom = rnd.Next(0, 31); // 0-30 inclusive
Console.WriteLine(iRandom);
Important Note: The upper bound is EXCLUSIVE (not included).
- Next(1, 11)
gives 1, 2, 3, ..., 10 (NOT 11)
- Next(0, 31)
gives 0, 1, 2, ..., 30 (NOT 31)
Generating Random Doubles
NextDouble() - Random Double from 0.0 to 1.0
Random rnd = new Random();
double dRandom = rnd.NextDouble();
Console.WriteLine(dRandom); // e.g., 0.7345921
// Random double in a specific range
double dMin = 10.0;
double dMax = 20.0;
double dValue = rnd.NextDouble() * (dMax - dMin) + dMin;
Console.WriteLine(dValue); // e.g., 15.723
Practical Examples from Course
Example 1: Random Number Statistics (From Worksheet 1)
using System;
namespace RandomStats
{
class Program
{
static void Main(string[] args)
{
Console.Write("How many random numbers: ");
int iN = int.Parse(Console.ReadLine());
Random rnd = new Random();
int iCountEven = 0, iCountOdd = 0;
int iSumEven = 0, iSumOdd = 0;
Console.WriteLine("\nRandom numbers generated:");
for (int i = 1; i <= iN; i++)
{
int iR = rnd.Next(0, 31); // Random 0-30
Console.Write(iR + " ");
if (iR % 2 == 0)
{
iCountEven++;
iSumEven += iR;
}
else
{
iCountOdd++;
iSumOdd += iR;
}
}
double dEvenPercentage = iCountEven * 100.0 / iN;
double dOddPercentage = iCountOdd * 100.0 / iN;
double dAvgEven = (iCountEven > 0) ? iSumEven * 1.0 / iCountEven : 0;
double dAvgOdd = (iCountOdd > 0) ? iSumOdd * 1.0 / iCountOdd : 0;
Console.WriteLine("\n\n--- Statistics ---");
Console.WriteLine($"Percentage of Even numbers: {dEvenPercentage:0.00}%");
Console.WriteLine($"Percentage of Odd numbers: {dOddPercentage:0.00}%");
Console.WriteLine($"Sum of even numbers: {iSumEven}");
Console.WriteLine($"Sum of odd numbers: {iSumOdd}");
Console.WriteLine($"Average of even numbers: {dAvgEven:0.00}");
Console.WriteLine($"Average of odd numbers: {dAvgOdd:0.00}");
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Example 2: Day Task Generator (From Worksheet 4)
using System;
namespace DayTaskGenerator
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
// Generate random day number (1-7)
int iDayNumber = random.Next(1, 8); // 1-7 inclusive
string sDayName;
string sTask;
switch (iDayNumber)
{
case 1:
sDayName = "Monday";
sTask = "Start the week with a team meeting!";
break;
case 2:
sDayName = "Tuesday";
sTask = "Tackle that big coding project!";
break;
case 3:
sDayName = "Wednesday";
sTask = "Midweek: Review progress and plan ahead!";
break;
case 4:
sDayName = "Thursday";
sTask = "Test and debug your code!";
break;
case 5:
sDayName = "Friday";
sTask = "Wrap up tasks and prepare for the weekend!";
break;
case 6:
sDayName = "Saturday";
sTask = "Relax or work on a personal project!";
break;
case 7:
sDayName = "Sunday";
sTask = "Plan for the upcoming week!";
break;
default:
sDayName = "Error";
sTask = "Invalid day selected!";
break;
}
Console.WriteLine($"Today is {sDayName}!");
Console.WriteLine($"Your task: {sTask}");
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Example 3: Monster Hunt Game (From Practical Test 4)
using System;
namespace MonsterHunt
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
Console.WriteLine("=== Monster Hunt ===");
Console.WriteLine("Choose your weapon (enter a number):");
Console.WriteLine("1. Sword");
Console.WriteLine("2. Bow");
Console.WriteLine("3. Magic Staff");
Console.Write("Your choice (1-3): ");
int iWeaponId = int.Parse(Console.ReadLine());
string sWeapon = "";
switch (iWeaponId)
{
case 1: sWeapon = "Sword"; break;
case 2: sWeapon = "Bow"; break;
case 3: sWeapon = "Magic Staff"; break;
default: sWeapon = "Fists"; break;
}
// Generate random monster (1-4)
int iMonsterId = random.Next(1, 5);
// Generate random loot (5-25 gold)
int iLootValue = random.Next(5, 26);
string sMonster = "";
string sOutcome = "";
switch (iMonsterId)
{
case 1:
sMonster = "Goblin Horde";
if (sWeapon == "Sword")
sOutcome = "You slash through the goblins with ease! Victory!";
else if (sWeapon == "Bow")
sOutcome = "Your arrows take out some goblins, but it's tough. Draw!";
else if (sWeapon == "Magic Staff")
sOutcome = "Your fireballs decimate the horde! Victory!";
else
sOutcome = "Your fists are no match for the horde. Defeat!";
break;
case 2:
sMonster = "Troll Brute";
// Similar outcomes...
break;
case 3:
sMonster = "Phantom Wraith";
// Similar outcomes...
break;
case 4:
sMonster = "Dire Wolf";
if (sWeapon == "Sword")
sOutcome = "You fend off the wolf with precise strikes! Victory!";
else if (sWeapon == "Bow")
sOutcome = "Your arrows keep the wolf at bay. Draw!";
else if (sWeapon == "Magic Staff")
sOutcome = "Your magic scares the wolf away. Victory!";
else
sOutcome = "Your fists aren't enough against the wolf. Defeat!";
break;
}
Console.WriteLine("\n=== Battle Result ===");
Console.WriteLine($"Weapon: {sWeapon}");
Console.WriteLine($"Monster: {sMonster}");
Console.WriteLine($"Outcome: {sOutcome}");
Console.WriteLine($"Loot Gained: {iLootValue} gold");
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Common Random Number Patterns
Pattern 1: Dice Roll (1-6)
Random rnd = new Random();
int iDiceRoll = rnd.Next(1, 7); // 1-6
Console.WriteLine($"You rolled: {iDiceRoll}");
Pattern 2: Coin Flip
Random rnd = new Random();
int iFlip = rnd.Next(0, 2); // 0 or 1
if (iFlip == 0)
{
Console.WriteLine("Heads");
}
else
{
Console.WriteLine("Tails");
}
Pattern 3: Random Boolean
Random rnd = new Random();
bool bRandomBool = rnd.Next(0, 2) == 0; // true or false
Pattern 4: Random Selection from Array
string[] sColors = { "Red", "Blue", "Green", "Yellow", "Purple" };
Random rnd = new Random();
int iIndex = rnd.Next(0, sColors.Length);
string sRandomColor = sColors[iIndex];
Console.WriteLine($"Random color: {sRandomColor}");
Pattern 5: Multiple Random Numbers
Random rnd = new Random();
Console.WriteLine("5 random numbers:");
for (int i = 0; i < 5; i++)
{
int iNumber = rnd.Next(1, 101); // 1-100
Console.WriteLine(iNumber);
}
Guessing Game Example
using System;
namespace GuessingGame
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int iSecretNumber = rnd.Next(1, 101); // 1-100
int iGuess = 0;
int iAttempts = 0;
Console.WriteLine("=== Number Guessing Game ===");
Console.WriteLine("I'm thinking of a number between 1 and 100");
while (iGuess != iSecretNumber)
{
Console.Write("\nEnter your guess: ");
iGuess = int.Parse(Console.ReadLine());
iAttempts++;
if (iGuess < iSecretNumber)
{
Console.WriteLine("Too low! Try again.");
}
else if (iGuess > iSecretNumber)
{
Console.WriteLine("Too high! Try again.");
}
else
{
Console.WriteLine($"\nCorrect! You guessed it in {iAttempts} attempts!");
}
}
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Random Array Shuffling
using System;
namespace ArrayShuffle
{
class Program
{
static void Main(string[] args)
{
int[] iNumbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Random rnd = new Random();
Console.WriteLine("Original array:");
PrintArray(iNumbers);
// Shuffle algorithm (Fisher-Yates)
for (int i = iNumbers.Length - 1; i > 0; i--)
{
int j = rnd.Next(0, i + 1);
// Swap
int iTemp = iNumbers[i];
iNumbers[i] = iNumbers[j];
iNumbers[j] = iTemp;
}
Console.WriteLine("\nShuffled array:");
PrintArray(iNumbers);
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
static void PrintArray(int[] iArr)
{
foreach (int iNum in iArr)
{
Console.Write(iNum + " ");
}
Console.WriteLine();
}
}
}
Practice Exercises
Exercise 1: Lottery Numbers
Generate 6 unique random numbers between 1 and 49 (no duplicates).
Exercise 2: Password Generator
Generate a random password with: - Random length (8-12 characters) - Mix of letters and numbers
Exercise 3: Rock Paper Scissors
Create a Rock-Paper-Scissors game against the computer.
Exercise 4: Random Quiz
Create a quiz that asks random questions from an array.
Exercise 5: Dice Game
Simulate rolling two dice 100 times and count how many times you get doubles.
Common Mistakes to Avoid
❌ Creating Random inside loop:
for (int i = 0; i < 10; i++)
{
Random rnd = new Random(); // WRONG! Same seed
Console.WriteLine(rnd.Next(1, 10));
}
✅ Correct:
Random rnd = new Random(); // Create once
for (int i = 0; i < 10; i++)
{
Console.WriteLine(rnd.Next(1, 10));
}
❌ Wrong range:
Random rnd = new Random();
int iDice = rnd.Next(1, 6); // WRONG! Gives 1-5, not 1-6
✅ Correct:
Random rnd = new Random();
int iDice = rnd.Next(1, 7); // Gives 1-6
❌ Forgetting upper bound is exclusive:
// Want 0-30 inclusive
int iNumber = rnd.Next(0, 30); // WRONG! Gives 0-29
✅ Correct:
int iNumber = rnd.Next(0, 31); // Gives 0-30
Key Takeaways
✅ Create Random object once, use multiple times
✅ Next(max)
generates 0 to max-1
✅ Next(min, max)
generates min to max-1 (max is excluded)
✅ Use NextDouble()
for decimal numbers (0.0-1.0)
✅ Don't create Random in loops
✅ Remember upper bound is EXCLUSIVE
✅ Perfect for games, simulations, and testing
Next Topic: C# String Methods and Manipulation