Search code examples
c#loopswhile-loop

How do i implement an until loop in c#


I am making a simple Higher, Lower game and I want the game to continue until the right number is guessed or if the guesser wants to restart. What loop do I use and how would I implement it

my code is

Random RandomNumber = new Random();
int RandomNumber2 = RandomNumber.Next(1, 5);
//Console.WriteLine(RandomNumber2);

//want to insert loop here and it should end when the third else if is done

Console.WriteLine("Make Your Guess Now");
string UserInput = Console.ReadLine();
int UserInput2 = Convert.ToInt32(UserInput);

if (UserInput2 > RandomNumber2)
{
    Console.WriteLine("Your Number is to high");
}
else if (UserInput2 < RandomNumber2)
{
    Console.WriteLine("Your Number is too small");
}
else if (UserInput2 == RandomNumber2)
{
    Console.WriteLine("Congrats on guessing the right number");
}

Solution

  • The standard way to do it is to use a do while loop (C# Reference).

    Bute here, you can use an infinite loop and exit from it using a break statement. This allows you to break out of the loop from a condition tested inside the loop

    ...
    Console.WriteLine("Make Your Guess Now");
    while (true) {
        string UserInput = Console.ReadLine();
        int UserInput2 = Convert.ToInt32(UserInput);
    
        if (UserInput2 > RandomNumber2)
        {
            Console.WriteLine("Your Number is too high. Make another guess");
        }
        else if (UserInput2 < RandomNumber2)
        {
            Console.WriteLine("Your Number is too small. Make another guess");
        }
        else
        {
            Console.WriteLine("Congrats on guessing the right number");
            break;
        }
    }
    

    Note that there is no need to test for UserInput2 == RandomNumber2 in the last else, since the other cases have been treated above, this is the only possibility remaining. Note that an else-part is executed when the if-part is not executed and only then.