do-while, break and continue

do-while

A do-while loop checks its condition at the end, so the block always runs at least once. It's great for asking the user until they give a good answer:

#include <stdio.h>

int main() {
    int number;
    do {
        printf("Enter a number from 1 to 10: ");
        scanf("%d", &number);
    } while (number < 1 || number > 10);
    printf("\nThanks, you chose %d\n", number);
    return 0;
}

Input (what the user types)

42
0
7

Output

Enter a number from 1 to 10: Enter a number from 1 to 10: Enter a number from 1 to 10: 
Thanks, you chose 7

Common mistake: A do-while loop needs a semicolon after the while (...) at the end.

break: leave the loop now

break stops the loop immediately, even if the condition is still true:

#include <stdio.h>

int main() {
    for (int i = 1; i <= 100; i++) {
        if (i * i > 50) {
            printf("First square over 50: %d x %d = %d\n", i, i, i * i);
            break;
        }
    }
    return 0;
}

Output

First square over 50: 8 x 8 = 64

continue: skip to the next round

continue skips the rest of this round and jumps to the next one:

#include <stdio.h>

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i % 3 == 0) {
            continue;    // skip multiples of 3
        }
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}

Output

1 2 4 5 7 8 10 

Think of it like this: break is like leaving a queue and going home. continue is like letting one person skip their turn while the queue keeps moving.

HOME LABS COMMUNITY DASHBOARD