do...while Loop in C Programming

Flow of a do while loop in C

A do...while loop executes its body first and checks the condition afterward. Because the test happens at the end, the body always runs at least once.

do...while Syntax Top ↑

do {
    // statements
} while (condition);

The semicolon after the closing while (condition) is required.

Print 1 to 5 Top ↑

#include <stdio.h>

int main(void) {
    int i = 1;

    do {
        printf("%d\n", i);
        i++;
    } while (i <= 5);

    return 0;
}

Output

1
2
3
4
5

The Body Runs Once Even When the Condition Is False Top ↑

#include <stdio.h>

int main(void) {
    int i = 50;

    do {
        printf("Executed once; i = %d\n", i);
    } while (i >= 100);

    return 0;
}

Output

Executed once; i = 50

This is the key difference from a while loop, which checks its condition before entering the body.

Avoid Infinite do...while Loops Top ↑

int i = 1;

do {
    printf("%d\n", i);
    // Missing i++ means i stays 1.
} while (i <= 5);

break in a do...while Loop Top ↑

#include <stdio.h>

int main(void) {
    int i = 1;

    do {
        if (i == 4) {
            break;
        }

        printf("%d\n", i);
        i++;
    } while (i <= 5);

    return 0;
}

Output

1
2
3

continue in a do...while Loop Top ↑

#include <stdio.h>

int main(void) {
    int i = 0;

    do {
        i++;

        if (i == 3) {
            continue;
        }

        printf("%d\n", i);
    } while (i < 5);

    return 0;
}

Output

1
2
4
5

In a do...while loop, continue jumps to the condition check at the bottom.

Decrement by 10 Top ↑

#include <stdio.h>

int main(void) {
    int i = 50;

    do {
        printf("%d\n", i);
        i -= 10;
    } while (i >= 0);

    return 0;
}

Output

50
40
30
20
10
0




plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer