Loops: for, while and do-while

Introduction

A loop repeats a block. C has three kinds, and each fits a different situation.

Repetition is what computers are best at. C's three loops give you precise control over exactly when a block repeats and when it stops, which matters greatly when you are working through memory one element at a time.

How it works

while: until something changes

#include <stdio.h>

int main(void) {
    int n = 4096;
    int count = 0, sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
        count++;
    }
    printf("%d digits, digit sum %d\n", count, sum);
    return 0;
}
Open in compiler

while checks its condition before each round. This loop takes the last digit with % 10 and removes it with / 10, until nothing is left.

do-while: at least once

A do { ... } while (condition); loop checks at the end, so its body always runs at least once. It suits menus that ask "again?".

break and continue

#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 10; i++) {
        if (i % 3 == 0) continue;
        if (i > 7) break;
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}
Open in compiler

continue jumps straight to the next round; break leaves the loop completely.

Syntax

for (int i = 0; i < n; i++) { ... }
while (n > 0) { ... }
do { ... } while (again);

Example

#include <stdio.h>

int main(void) {
    int sum = 0;
    for (int i = 1; i <= 5; i++) {
        sum += i;
    }
    printf("1 + 2 + ... + 5 = %d\n", sum);
    return 0;
}
Open in compiler

for (int i = 1; i <= 5; i++) has three parts:

  1. int i = 1 runs once, before the loop starts.
  2. i <= 5 is checked before every round. When it is false, the loop ends.
  3. i++ runs after every round.

Step through and watch i and sum change. On the last check, the calculation box shows i <= 5 → 6 <= 5 → false, and the loop ends.

Line by line

  1. sum starts at 0, outside the loop.
  2. int i = 1 runs once, before the first round.
  3. i <= 5 is checked before each round, and it is true while i is at most 5.
  4. sum += i adds the current value.
  5. i++ runs after each round, and the loop ends when i becomes 6.

Expected result

1 + 2 + ... + 5 = 15

In the real world

A loop reads each byte of a file, updates each pixel of a screen and checks each packet that reaches a router. In embedded systems, the whole program is often one loop that never ends on purpose.

Common mistakes

  • An endless loop: the condition never becomes false (for example, forgetting n /= 10). StepVioz stops it after a number of steps.
  • for (int i = 0; i <= n; i++) when you meant i < n: one round too many. This is how arrays get overrun.
  • A ; right after for (...): the loop then repeats nothing, and the block below runs once.

Best practices

  • Declare the loop variable inside the for.
  • Write the stop condition as i < n when you count from 0.
  • Make sure that something changes the condition on every round.

Summary

for counts, while repeats until its condition fails, and do-while always runs once. break leaves a loop, and continue jumps to the next round.

Quick check

1. How many times does this run? for (int i = 0; i < 5; i++)
2. Which loop always runs its body at least once?
3. What does continue do?

Key takeaways

  • Use for when you can count the rounds.
  • do-while always runs at least once.
  • Check where each loop starts and stops.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.