The while Loop

Why loops?

Imagine printing the numbers 1 to 100. Writing 100 printf lines would be silly. A loop repeats code for you.

while

A while loop keeps running its block while its condition is true:

#include <stdio.h>

int main() {
    int count = 1;
    while (count <= 5) {
        printf("Count: %d\n", count);
        count++;
    }
    printf("Done!\n");
    return 0;
}

Output

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Done!

Step by step:

  • count starts at 1.
  • Is count <= 5? Yes, so print it and add 1.
  • Check again... and again... until count is 6.
  • Now the condition is false, so the loop stops and C moves on to Done!.

Think of it like this: A while loop is like eating soup: while there is still soup in the bowl, take another spoonful. You check before each spoonful.

Loops that never end

Common mistake: Forgetting to change the variable. If count++ is missing above, count stays 1 forever, the condition is always true, and the program never stops. This is an infinite loop.

Reading until a stop value

while is perfect when you don't know in advance how many times to repeat. This program adds up numbers until the user types 0:

#include <stdio.h>

int main() {
    int number;
    int total = 0;
    scanf("%d", &number);
    while (number != 0) {
        total += number;
        scanf("%d", &number);
    }
    printf("Total: %d\n", total);
    return 0;
}

Input (what the user types)

5
10
3
0

Output

Total: 18

Remember: A while loop checks its condition before every round. Make sure something inside the loop eventually makes the condition false.

HOME LABS COMMUNITY DASHBOARD