- 7th Apr 2023
- 09:21 am
C# Homework Question - C# Logical Puzzles, Games, and Algorithms: Roll of Dice
C# Homework Solution
Here's an example C# program for simulating the roll of two dice:
using System;
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
while (true)
{
Console.WriteLine("Press enter to roll the dice, or type 'quit' to exit.");
string input = Console.ReadLine();
if (input == "quit")
{
break;
}
int roll1 = rand.Next(1, 7);
int roll2 = rand.Next(1, 7);
Console.WriteLine("You rolled a {0} and a {1}.", roll1, roll2);
if (roll1 + roll2 == 7)
{
Console.WriteLine("You win!");
}
else
{
Console.WriteLine("You lose.");
}
}
}
}
This program uses the Random class to generate random integers between 1 and 6 (inclusive) for the two dice rolls. It then checks if the sum of the two rolls is equal to 7, and prints "You win!" if it is, or "You lose." if it isn't. The program continues to loop until the user types "quit" to exit.