Building A Guessing Game

Lesson 19
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

Here’s an example of how to build a simple guessing game using a while loop in C#:

using System;

class Program
{
    static void Main(string[] args)
    {
        // Generate a random number between 1 and 100
        Random random = new Random();
        int number = random.Next(1, 101);

        // Prompt the user to guess the number
        Console.WriteLine("I'm thinking of a number between 1 and 100. Can you guess what it is?");

        // Keep asking the user to guess until they get the correct answer
        int guess = 0;
        while (guess != number)
        {
            // Read the user's guess from the console
            Console.Write("Enter your guess: ");
            guess = int.Parse(Console.ReadLine());

            // Compare the user's guess to the random number
            if (guess < number)
            {
                Console.WriteLine("Your guess is too low. Try again.");
            }
            else if (guess > number)
            {
                Console.WriteLine("Your guess is too high. Try again.");
            }
            else
            {
                Console.WriteLine("Congratulations! You guessed the number.");
            }
        }

        // Wait for the user to press a key before closing the console window
        Console.Write("Press any key to exit...");
        Console.ReadKey();
    }
}

In this example, we’re using the Random class to generate a random number between 1 and 100. We’re then using a while loop to keep asking the user to guess the number until they get it right. Inside the loop, we’re using an if-else statement to compare the user’s guess to the random number and provide feedback (i.e., “too low”, “too high”, or “correct”). Once the user guesses the number correctly, the loop ends and the program exits.

Note that we’re also using Console.ReadLine() and int.Parse() to read the user’s input from the console and convert it to an integer data type, respectively. We’re also using Console.ReadKey() to wait for the user to press a key before closing the console window.