Skip to content
FollowtheDamnCode

The while Loop

Repeat while a condition is true.

5 minute read

Big idea

A while loop repeats a block as long as its condition stays true.

The idea

while (condition) {
    // repeats while condition is true
}

Before every round, C checks the condition. True → run the block, then check again. False → skip past the loop and carry on.

Almost every loop has three parts:

  1. Start — set up a variable before the loop: int i = 1;
  2. Check — the condition: while (i <= 3)
  3. Change — move towards the end inside the loop: i = i + 1;

Watch it run

Step through line by line and watch i change:

When you don't know how many rounds

while shines when the number of rounds depends on the data. How many digits does a number have? Keep dividing by 10 until nothing's left:

Count the digits — try your own number
#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);
    int digits = 0;
    while (n > 0) {
        n = n / 10;
        digits = digits + 1;
    }
    printf("%d digits\n", digits);
    return 0;
}
input
90210
output
5 digits

Run and edit it in the app.

Watch it

Think of it like

Stirring soup: "while it's not boiling, keep stirring." You don't know how many stirs it'll take — you just keep checking.

🕷️ Spidey-sense: while (city_in_danger) { patrol(); } — the day I forget to make the danger go down inside that loop is the day I never get home for dinner.

Common mistake

Forgetting the change step. If nothing inside the loop moves the condition towards false, it never ends — an infinite loop:

Fix the bug: print 1 to 3, then stop
#include <stdio.h>

int main(void) {
    int i = 1;
    while (i <= 3) {
        printf("%d\n", i);
    }
    return 0;
}
output
1
2
3

Run and edit it in the app.

(Running it stops after the time limit — that's the app protecting you from a loop that never ends.)

Key terms

  • Loop — Code that repeats.
  • Iteration — One round of a loop.
  • Infinite loop — A loop whose condition never becomes false.

Check yourself

When does a while loop check its condition?

What causes an infinite loop?

int i = 10; while (i < 5) { i++; } How many rounds?