Difference Between While and Do While in C: Entry vs Exit Condition

In C, understanding the difference between while and do while loops can greatly improve the quality of input validation and event loops. While and do while are identical except that while tests the condition at the top, so the body will never be executed if the condition is initially false, do while tests the condition at the bottom, so the body will be executed at least once if the condition is initially false. Thus, do-while loop is useful for interactive CLI menus and retry prompts to ensure that it will always be executed at least once.

Difference Between While and Do While Loop in C — Technical Overview

In C, understanding the difference between while and do while loops can greatly improve the quality of input validation and event loops. While and do while are identical except that while tests the condition at the top, so the body will never be executed if the condition is initially false, do while tests the condition at the bottom, so the body will be executed at least once if the condition is initially false. Thus, do-while loop is useful for interactive CLI menus and retry prompts to ensure that it will always be executed at least once.

#include <stdio.h>

int main(void) {
    int count = 0;
    while (count > 0) {
        printf("while body\n");
    }
    do {
        printf("do-while runs at least once (count=%d)\n", count);
    } while (count > 0);
    return 0;
}

Runnable C example

#include <stdio.h>

int main(void) {
    int count = 0;
    while (count > 0) {
        printf("while body\n");
    }
    do {
        printf("do-while runs at least once (count=%d)\n", count);
    } while (count > 0);
    return 0;
}

Open example in compiler

Expected Output

do-while runs at least once (count=0)