Search code examples
c#for-loopwhile-loopconsole-application

I'm trying to write a simple program that picks a random number between 1 and 10 and gives the user to guess it


I'm new to C# and I'm struggling a bit with loops. For this one, I'm trying to use the 'for' loop. I have tried various options - for, while loops, but I wasn't able to reach the desired result.

For this one, the says I lost, even if I "guessed" the number.

{
    var random = new Random();
    int random2 = Convert.ToInt32(random.Next(0, 10));

    Console.WriteLine(random2);


    for  (var i = 4; i <= 4; i++)
    {
        Console.WriteLine("Please enter a number from 0 to 10:");
        var input = Convert.ToInt32(Console.ReadLine());

        if (input != random2)
        {
            Console.WriteLine("You have {0} tries left.", i - 1);
            continue;

        }

        if (input != random2)
        {
            Console.WriteLine("You have {0} tries left.", i - 1);
            continue;
        }

        if (input != random2)
        {
            Console.WriteLine("You have only {0} try left!!", i - 1);
            continue;
        }

        if (input == random2)
        {
            Console.WriteLine("You lose!!!");
            break;
        }

        if (input == random2)
        {
            Console.WriteLine("You have won!!!!!");
            break;
        }

    }
}

What I'm trying to do: write a program that picks a random number between 1 and 10 and gives the user 4 chances to guess it. However, I want to make the console print the remaining number of tries and print a different message when the user is on their last try.


Solution

  • Let's implement from scratch step by step:

    1. Let's start from comments (what we are going to do)
    2. Let's use proper names (attempt instead of i)
    // Computer pick the number in 1..9 range
    int picked = Random.Shared.Next(1, 10);
    // We have 4 attempts
    int attempts = 4;
    
    // We haven't found the picked number yet
    bool found = false;
    
    // for each attempt
    for (int attempt = 1; attempt <= attempts; ++attempt) {
      // We are asked to guess
      Console.WriteLine("Please enter a number in 1 .. 9 range:");
    
      // We do our guess - note, int.TryParse is a better option
      int guess = int.Parse(Console.ReadLine()); 
    
      // If we guess right then ...
      if (guess == picked) {
        // ... the picked number is found and  
        found = true;
        // we don't want any attempt more
        break; 
      }
    
      // if we don't guess right, show number of attempts 
      Console.WriteLine($"You have {attempts - attempt + 1} tries left.");
    } 
    
    // after all attempts show outcome
    if (found)
      Console.WriteLine("You have won!!!!!");
    else
      Console.WriteLine("You have lost.");