Skip to content

break, continue and do-while

Read · 1 of 4

Changing a loop's course

break leaves the loop immediately. continue skips the rest of this turn and goes to the next one.

do { … } while (condition); runs the body first and checks afterwards, so it always runs at least once. Handy for "keep reading until …".

Read this lesson as text

Leave a loop early, skip a turn, and loops that run at least once.

Changing a loop's course

break leaves the loop immediately. continue skips the rest of this turn and goes to the next one.

do { … } while (condition); runs the body first and checks afterwards, so it always runs at least once. Handy for "keep reading until …".

Skip and stop

#include <stdio.h>

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

What does this print (spaces included)?

  • 1 2 4 5 7
  • 1 2 4 5 7 8 10
  • 1 2
Show the answer

1 2 4 5 7 Multiples of 3 are skipped. At 8 the loop breaks, so 8 and 10 never print.

Exercise: Add until zero

Read whole numbers one by one until a 0 arrives. Print how many numbers came before the 0, and their sum: 3 15.

Break it: Break the prime checker

This should print Prime or Not prime for n. Find an n where it's wrong.

#include <stdio.h>

int main() {
    int n, prime = 1;
    scanf("%d", &n);
    for (int d = 2; d < n; d++) {
        if (n % d == 0) {
            prime = 0;
            break;
        }
    }
    printf(prime ? "Prime\n" : "Not prime\n");
    return 0;
}

Input rules: one whole number n between 1 and 10000.