Home > Net >  How do I solve the infinite loop so it can keep asking the user to enter a number?
How do I solve the infinite loop so it can keep asking the user to enter a number?

Time:09-27

I am having trouble figuring out my do-while loop. You enter a number from 1-4 and if it is correct, it'll terminate. But if !(1-4) repeat the loop again to type the number again. I have it where my else statement keeps printing an infinite loop. How do I solve the infinite loop so it can keep asking the user to enter a number?

Code:

cin >> num;
do
{
    if (num == 1 || num == 2 || num == 3 || num == 4)
    {
        cout << "Correct\n";
    }
    else
    {
        cout << "Incorrect. Try Again\n";
    }
}
while ((num != 1) && (num != 2) && (num != 3) && (num != 4));

CodePudding user response:

Your loop never updates the value of num, so if the loop enters, it can never end.

You likely wanted:

do
{
    cin >> num;
    if (num >= 1 && num <= 4)
    {
        cout << "Correct\n";
    } 
    else
    {
        cout << "Incorrect. Try Again\n";
    }
} while (num < 1 && num > 4);

Alternatively, you are checking that condition twice. You don't need to do this when you can use break to break the loop on correct input.

while (true) {
    cin >> num;
    if (num >= 1 && num <= 4) {
        cout << "Correct\n";
        break;
    }
    else {
        cout << "Incorrect. Try Again\n";
    }
}

CodePudding user response:

If you want the user to be able to enter input more than once (for example if the previous input was incorrect), then you must move the line

cin >> num;

inside the loop.

In order to prevent having the condition

num == 1 || num == 2 || num == 3 || num == 4

twice in your code (the second one is identical, except negated), it would be better to write this condition only once. Also, you can simpify it to the following:

1 <= num && num <= 4

I recommend you rewrite the loop to the following:

for (;;) //infinite loop, equivalent to while(true)
{
    cin >> num;

    if ( 1 <= num && num <= 4 )
    {
        cout << "Correct.\n";
        break;
    }

    cout << "Incorrect. Try Again.\n";
}
  •  Tags:  
  • c
  • Related