Search code examples
c#while-loopdo-while

While Loop Going Infinitely Long


I want the code to continue running until a user guesses the correct answer. However the code runs something else infinitely.

public class Quiz{
    //Make various questions with correct/incorrect options
    /*
    * Suggestion
    * Question 1
    * How old was the first king of sweden when he passed?
    * Options1
    * 40
    * 60
    * 80
    */
    public static int correctAnswer = 40;
    public static int guess = Convert.ToInt32(Console.ReadLine());

    public static void Guess(){
        System.Console.WriteLine("How old was the 1st King of Sweden\n");
        System.Console.WriteLine("when he passed away?");
     while(guess != correctAnswer){
        if(guess == correctAnswer){
            System.Console.WriteLine("Correct answer. Congratulations.");
        } else{
            System.Console.WriteLine("Try again.");
        }
     }
    }
}

I tried changing from do-while to while but that did not help.


Solution

  • you never assign anything to guess after it was set the very first time. You need to re-assign guess in every iteration:

    public static int correctAnswer = 40;
    
    public static void Guess()
    {
        System.Console.WriteLine("How old was the 1st King of Sweden\n");
        System.Console.WriteLine("when he passed away?");
        var guess = Convert.ToInt32(Console.ReadLine());
        while(guess != correctAnswer)
        {
            System.Console.WriteLine("Try again.");
            guess = Convert.ToInt32(Console.ReadLine());
        }
    
        // when we reach the end of the loo, user gave a correct answer
        System.Console.WriteLine("Correct answer. Congratulations.");
    }