P2: Number Guessing
Program 2: Number Guessing Game
This program introduces loops and more complex conditionals. It's a simple game where the user has to guess a randomly generated number.
Random random = new Random();
int randomNumber = random.Next(1, 101); // Random number between 1 and 100
int attempts = 0;
int userGuess = 0;
Console.WriteLine("Guess the number (1-100)!");
while (userGuess != randomNumber)
{
Console.Write("Enter your guess: ");
userGuess = Convert.ToInt32(Console.ReadLine());
attempts++;
if (userGuess < randomNumber)
{
Console.WriteLine("Too low, try again.");
}
else if (userGuess > randomNumber)
{
Console.WriteLine("Too high, try again.");
}
}
Console.WriteLine($"Congratulations! You guessed the number in {attempts} attempts.");
Last updated