Lesson 4 of 6 · Control Flow · 3 min read · Updated

Loops: while, do-while, and for

Three ways to repeat work, and how to choose between them.

Printing 1 to 100 by hand would be a hundred lines. A loop does it in three.

A for loop: set up once, test, run the body, step — then test again until the test is false.

for — when you know how many times

c
for (int i = 1; i <= 5; i++) {
    printf("%d ", i);
}
printf("\n");
Output
1 2 3 4 5

The three parts of a for loop

  1. int i = 1

    The setup. Runs once, before anything else. This is where the counter starts.

  2. i <= 5

    The test. Checked before every pass. While it is true the loop keeps going; the moment it is false the loop ends.

  3. i++

    The step. Runs after each pass, before the test is checked again. Forget this and the loop never ends.

while — when you do not know how many times

c
int n;

printf("Enter a number (0 to stop): ");
scanf("%d", &n);

while (n != 0) {
    printf("You typed %d\n", n);
    printf("Another (0 to stop): ");
    scanf("%d", &n);
}

do-while — when it must run at least once

c
int choice;

do {
    printf("1. Start  2. Help  3. Quit\n");
    printf("Choice: ");
    scanf("%d", &choice);
} while (choice < 1 || choice > 3);

Note

The difference is when the test happens. while checks before the first pass, so it may run zero times. do-while checks after, so it always runs at least once. Menus want do-while.

Warning

An infinite loop happens when the condition never becomes false — usually because you forgot to change the variable it tests. Press Ctrl+C to stop a runaway program.

break and continue

c
for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        continue;   /* skip just this pass */
    }
    if (i == 8) {
        break;      /* leave the loop entirely */
    }
    printf("%d ", i);
}
Output
1 2 3 4 6 7

Which loop always runs its body at least once?

Try this now

  1. Print the multiplication table for a number the user chooses.
  2. Add up the numbers from 1 to 100 with a loop, and print the total.
  3. Read numbers until the user types 0, then print how many were positive.

Create a free account to save your progress, or sign in.