> For the complete documentation index, see [llms.txt](https://raviram.gitbook.io/c-programing/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://raviram.gitbook.io/c-programing/problem-based-learning/p2-number-guessing.md).

# 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.

```csharp
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.");
```
