user5379214
user5379214

Reputation:

Do... While loop counter implementation not working

I created a program in C# (Console Application), which prompts the user to enter the answer to "2+2=?", if its right a message pops up "Well done", if not then "Please try again". What I am trying to do is make the program tell the user how many guesses/attempts they have made before getting the correct answer.

This is what I have done so far

class Program
{
    public static int correct_answer, counter,  user_answer, counterUpdated;

    static void Main(string[] args)
    {
        correct_answer = 4;

        do 
        {
            counter = 1;
            counterUpdated = counter++;

            Console.WriteLine("2+2= ?");
            user_answer = Convert.ToInt32(Console.ReadLine());

            if (user_answer != correct_answer)
            {
                Console.Clear();
                Console.WriteLine("Wrong, try againg" + " this is your " + counterUpdated + " try.");
            }
        } while (user_answer != correct_answer); // The code will keep looping until the user prompts the correct answer 

        Console.Clear();
        Console.WriteLine("Well Done! you did it in this amount of guesses " + counterUpdated);
        Console.ReadLine();
    }
}

If someone could tell me how to make the counter thing work, that would be great.

Upvotes: 0

Views: 441

Answers (2)

fahimalizain
fahimalizain

Reputation: 844

Tweaked a bit, and this should work :)

class Program
{
    public static int correct_answer, counter,  user_answer;

    static void Main(string[] args)
    {
        correct_answer = 4;
        counter = 0;
        do 
        {

            counter++;

            Console.WriteLine("2+2= ?");
            user_answer = Convert.ToInt32(Console.ReadLine());

            if (user_answer != correct_answer)
            {

                Console.Clear();
                Console.WriteLine("Wrong, try againg" + " this is your " + counter+ " try.");

            }



        } while (user_answer != correct_answer); // The code will keep looping until the user prompts the correct answer 
        Console.Clear();
        Console.WriteLine("Well Done! you did it in this amount of guesses " + counter);
        Console.ReadLine();



    }
}

What i did was i removed the counterUpdated variable and had the counter variable do all the counting work :)

Hope it helped :)

Upvotes: 1

John3136
John3136

Reputation: 29266

You always set counter to 1 at the start of the loop, then immediately counterUpdated = counter++; (which is a bit odd anyway...). Just do it with one counter that you initialize outside the loop and increment inside the loop.

int guessNumber = 0;
do {
    guessNumber++;
    // ...

Upvotes: 2

Related Questions