Infinite Loops
If the condition of a while loop never becomes false, the loop never ends. This is called an infinite loop (or an endless loop), and it's one of the most common mistakes with loops. Here, the line number++ is missing:
int number = 1;
while (number <= 5) {
printf("%d\n", number);
}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)withnumber++instead ofnumber--makesnumberbigger 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. - A semicolon after the condition.
while (number <= 5);ends with a semicolon, and that semicolon is everything the loop repeats: an empty statement, forever. The block in curly braces below it doesn't belong to the loop at all. The program prints nothing and is stopped after 5 seconds. Never put a semicolon between)and{. - 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.
Sometimes you see RuntimeError: unreachable instead of the message about running too long. You know it from the lesson on variables: a number got too big for an int (bigger than 2147483647, about two billion). In an endless loop, this happens mostly when the loop only calculates and prints nothing. Then it runs very fast, and a variable keeps growing until it doesn't fit. The fix is the same: find the loop that never ends.
Instructions
The program in the editor should print the odd numbers from 1 to 9 and then Done. Run it: it doesn't stop by itself, and after 5 seconds it 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
2/11