← Back

Activity 2.7 Number Guessing Game


Introduction

All sorts of simple, but fun programs can be created with a few simple loops and if statements. For example, this simple little guessing game can be created with a basic while loop.

Skills to Practice


Instructions

Setup

  1. Create a new C# console application. Name the project 2.7 Number Guessing Game.
  2. Click Create.

Code

Random random = new();
int secretNumber = random.Next(1, 11); // Number between 1 and 10
int tries = 0; // Track the number of tries
int guess = 0; // Any default number not between 1 and 10 is fine

while (guess != secretNumber)
{
    Console.Write("Guess the number (1-10): ");
    guess = Convert.ToInt32(Console.ReadLine());
    tries = tries + 1;

    if (guess == secretNumber)
    {
        Console.WriteLine($"Correct! It took you {tries} tries!");
    }
    else if (guess > secretNumber)
    {
        Console.WriteLine("Wrong! Too high.");
    }
    else
    {
        Console.WriteLine("Wrong! Too low.");
    }
}

Debug

Guess the number (1-10): 1
Wrong! Too low.
Guess the number (1-10): 9
Wrong! Too high.
Guess the number (1-10): 6
Wrong! Too high.
Guess the number (1-10): 5
Correct! It took you 4 tries!

Tips, Tricks, and Reflection