Lesson contents

C — While loops and their stopping conditions

A while loop tests its condition before each iteration. If the first test is false, the body executes zero times.

A simple example

Print while the number is at most 3

  1. Start with n starts at 1
  2. Do this Print n, add 1
  3. Result Stop at 4
The test happens before each print. It succeeds for 1, 2 and 3. At 4 it fails, so 4 is never printed.
lesson.c
#include <stdio.h>

int main(void) {
    int n = 1;
    while (n <= 3) {
        printf("%d\n", n);
        n++;
    }
}
Output
1
2
3
Advertisements

Pack whole batches from stock

Count complete batches of five items by repeatedly removing five while enough stock remains. Keep the leftover units for the next order. Subtracting the positive batch size makes progress toward termination. Packing a final exact batch is possible because the condition uses >=.

Apples at the start: 17. Bag size: 5 apples. Packed: 3 bags · 2 left.
Fill complete snack bags

The canteen has 17 apples and packs five in each bag. Check the remaining pile before filling each bag. Three full bags leave two apples for the next delivery.

Run the example

Use a C17 compiler. Run these commands from the directory containing the example. Use a Unix-style shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson
lesson.c
#include <stdio.h>

int main(void) {
    int stock = 17;
    int batches = 0;
    while (stock >= 5) {
        stock -= 5;
        ++batches;
    }
    printf("%d batches, %d left\n", batches, stock);
    return 0;
}
Output
3 batches, 2 left

Seventeen items shrink to 12, 7, then 2. The condition is tested again at 2 and the body stops after three batches.

Try it yourself

What happens with four items? What about exactly five?

Check your answer

Four items yield zero batches and four leftovers. Five items yield one batch and no leftovers because the comparison includes equality.

WG14 C language draft (PDF)

Related tags

  • C
  • while loops
  • loop conditions
  • termination