Infinite Loops

If the condition of a while loop never becomes false, the loop never ends. This is called an infinite loop, and it's one of the most common mistakes with loops. Here, the line number++ is missing:

int number = 1;
while (number <= 5) {
    std::cout << number << std::endl;
}

number stays 1, the condition number <= 5 is always true, and the program prints 1 over and over:

1
1
1
1
...

On your own computer, such a program would run until you stopped it. In these exercises, it is stopped after 5 seconds, and you see the message The program ran too long and was stopped. Does it have a loop that never ends? When you see it, check every loop: does something in its block change the variable in the condition, so that the condition becomes false at some point?

Typical causes:

  • Nothing changes the variable, as in the example above.
  • The variable changes in the wrong direction. A countdown while (number >= 1) with number++ instead of number-- makes number bigger and bigger, so the condition stays true.
  • The change is outside the block. Only the code between the curly braces repeats. If number++ ends up below the closing brace }, it would run only after the loop, and that never comes. The same happens if you leave out the braces: then only the first statement after the condition belongs to the loop. That's why you should always write them, even when the block has only one line.
  • The condition misses its goal. A condition with != (not equal) is true for every number except one. If the variable jumps over that one number, the loop goes on forever. That's why counting loops usually use <, <=, > or >=: they stop even when the variable skips past the limit.

Instructions

The program in the editor should print the odd numbers from 1 to 9 and then Done. Run it: the numbers keep growing, and after 5 seconds the program is stopped. Find out why the condition never becomes false, and fix it, so that the program prints 1, 3, 5, 7, 9 and Done, each on its own line.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

2/13