Guess the Number Challenge in C#
- January 6, 2025
- Posted by: admin
- Categories:
int secretNumber = 10; //First we initialize the secret number by the line int SecretNumber = 10;
int userGuess = 0; /*This line is to make sure that before we bring in the while loop,
//we have something to compare for either a true result. In this case, we are comparing SecretNumber & userGuess variables. */
while (secretNumber != userGuess) /*The while loop condition needs to return either a false or true result. In this case, the condition is already
false since secretNumber is not equal to userGuess */
{
Console.WriteLine(“Enter your guess:”); // The compiler runs this code and prompts the user to enter a guess
userGuess = int.Parse(Console.ReadLine()); /*The compiler reads what the user has entered and converts it into an integer using the int.Parse() method */
if (userGuess < secretNumber) //The compiler checks what the user has entered and if its less that 10 { Console.WriteLine(“Too low, try again”); // if what the user has entered is less than 10, then the user will get this message } else if (userGuess > secretNumber) // Compiler checks if what the user has entered is greater than 10
{
Console.WriteLine(“Too high, try again”); //if what the user has entered is greater than 10, then the user will get this message
}
else
Console.WriteLine(“Congratulations, you guessed it right”); /*if what the user has entered is neither greater or less than 10, it means, it
matches the secretNumber so the user gets this message */