Course contentsShow
← C
Lesson 275 of 1,2194. Control FlowFree lesson

Guaranteed execution: why do-while is different

Guaranteed execution: why do-while is different

What you'll learn: You will understand how the do-while loop ensures your code runs at least once, even if the condition is false from the very start.

The "Act First, Ask Later" Approach

Imagine you are at a buffet. In a standard while loop, the waiter stops you at the door and asks, "Do you have a ticket?" If you don’t, you never even step inside. The condition is checked before the action.

The do-while loop works differently. It’s like a "Taste Test." The waiter says, "Go ahead and try one bite, then we’ll check if you want to stay for the whole meal." You get that first bite no matter what. In programming, we call this post-test logic. Because the condition is at the bottom, the code block is guaranteed to execute at least one time.

Seeing it in Action

This is particularly useful for things like menus or user input. You want to show the user the options at least once before checking if they want to quit.

#include <stdio.h>

int main() {
    int choice = 0;

    do {
        printf("--- Secure Vault ---\n");
        printf("1. View Balance\n");
        printf("2. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
        
        // This loop runs once to show the menu, 
        // then repeats ONLY if the user didn't pick 2.
    } while (choice != 2);

    printf("Goodbye!\n");
    return 0;
}

Notice the syntax: the do keyword starts the block, and the while condition sits at the very end, followed by a semicolon (;).

Why does this matter?

If we used a regular while loop here and initialized choice to 2 by accident, the menu would never appear. With do-while, the computer executes the code inside the curly braces first, hits the while statement at the bottom, and only then decides whether to jump back to the top.

Use this loop whenever the "setup" and the "check" are the same thing. It saves you from writing the same code twice—once before the loop and once inside it.

Key takeaway

A do-while loop guarantees the code block runs at least once because it checks the condition after execution, not before.