C/C++ Arena

Step 1 of 7

while loops

Computers are good at doing the same thing many times. A loop repeats a block of code. The simplest is while: it checks a condition, and if it's true, runs the body, then checks again, and so on until the condition is false.

#include <stdio.h>

int main(void) {
    int lives = 3;
    while (lives > 0) {
        printf("lives left: %d\n", lives);
        lives--;
    }
    printf("game over\n");
    return 0;
}
lives left: 3
lives left: 2
lives left: 1
game over

Trace it

Tracing a loop by hand (writing down each variable after every pass) is the best way to understand it:

Check lives > 0 Prints lives after
3 > 0 true lives left: 3 2
2 > 0 true lives left: 2 1
1 > 0 true lives left: 1 0
0 > 0 false (loop ends) 0

The condition is checked before each pass, so if it's false at the start, the body never runs at all.

Every loop needs progress

Something in the body must eventually make the condition false. Here it's lives--. If you forget it, lives stays 3 forever and the loop never ends: an infinite loop. On this site, a program that runs longer than 3 seconds is stopped with a time-limit message. On your own computer, press Ctrl+C to stop it.

Your turn: read n and count down from n to 1, one number per line, then print GO!.

Next: for loops