C Do-While Loop

Execute code at least once, then check condition

🔄 What is a Do-While Loop?

A do-while loop in C executes code first, then checks the condition. It guarantees at least one execution, making it perfect for menus and input validation where you need to run code before testing.


// Simple do-while loop example
#include <stdio.h>

int main() {
    int count = 1;
    do {
        printf("Execution: %d\n", count);
        count++;
    } while(count <= 3);
    return 0;
}
                                    

Output:

Execution: 1
Execution: 2
Execution: 3

Do-While vs While Loop

🔄

While Loop

Check condition first

while(condition) {
    // code
}
▶️

Do-While Loop

Execute first, then check

do {
    // code
} while(condition);

May Not Execute

If condition is false initially

int x = 10;
while(x < 5) {
    // Never runs
}

Always Executes Once

Guaranteed first execution

int x = 10;
do {
    // Runs once
} while(x < 5);

🔹 Do-While Loop Syntax

The do-while loop executes its body at least once before checking the condition, with a mandatory semicolon after the while clause. The syntax structure is do { statements; } while(condition); where the semicolon is required and often causes compilation errors if forgotten. This loop variant guarantees that the loop body runs at least once regardless of the initial condition state, making it ideal for menu-driven programs, input validation requiring at least one attempt, and scenarios where initialization happens inside the loop body. For example, do { printf("Enter value: "); scanf("%d", &val); } while(val < 0); prompts the user at least once before validating input, ensuring interactive programs always request user input before checking validity.

do {
    // Code to execute
    // Update variables here
} while(condition);  // Don't forget the semicolon!

// Example: Print numbers even if condition is false
#include <stdio.h>

int main() {
    int i = 10;
    
    do {
        printf("i = %d\n", i);
        i++;
    } while(i < 5);  // Condition is false, but code runs once
    
    return 0;
}

Output:

i = 10

🔹 Perfect Use Cases

🔸 Menu System

#include <stdio.h>

int main() {
    int choice;
    
    do {
        printf("\n=== MENU ===\n");
        printf("1. Option A\n");
        printf("2. Option B\n");
        printf("3. Exit\n");
        printf("Enter choice: ");
        scanf("%d", &choice);
        
        switch(choice) {
            case 1: printf("You chose Option A\n"); break;
            case 2: printf("You chose Option B\n"); break;
            case 3: printf("Goodbye!\n"); break;
            default: printf("Invalid choice!\n");
        }
    } while(choice != 3);
    
    return 0;
}

Sample Run:

=== MENU ===
1. Option A
2. Option B
3. Exit
Enter choice: 1
You chose Option A

=== MENU ===
1. Option A
2. Option B
3. Exit
Enter choice: 3
Goodbye!

🔸 Password Validation

#include <stdio.h>
#include <string.h>

int main() {
    char password[20];
    char correct[] = "secret123";
    
    do {
        printf("Enter password: ");
        scanf("%s", password);
        
        if(strcmp(password, correct) != 0) {
            printf("Wrong password! Try again.\n");
        }
    } while(strcmp(password, correct) != 0);
    
    printf("Access granted!\n");
    return 0;
}

Sample Run:

Enter password: wrong
Wrong password! Try again.
Enter password: secret123
Access granted!

🔹 Key Differences Demonstration

Understanding the fundamental difference between while and do-while loops is essential for choosing the correct loop construct for specific programming scenarios. A while loop checks the condition before the first iteration, potentially never executing the loop body if the condition is initially false. But a do-while loop always executes its body at least once before checking the condition. For example, int x=10; while(x<5) { printf("Never runs"); } prints nothing, but do { printf("Runs once"); } while(x<5); prints "Runs once". Choose do-while for input validation, menu systems, and initialization-required operations, while while loops suit conditional repetition where execution may not be needed at all.

🔸 While Loop (May Not Execute)

#include <stdio.h>

int main() {
    int x = 5;
    printf("While loop:\n");
    while(x < 3) {
        printf("This won't print\n");
        x++;
    }
    printf("x = %d\n", x);
    return 0;
}

Output:

While loop:
x = 5

🔸 Do-While Loop (Always Executes Once)

#include <stdio.h>

int main() {
    int x = 5;
    printf("Do-while loop:\n");
    do {
        printf("This prints once: x = %d\n", x);
        x++;
    } while(x < 3);
    printf("Final x = %d\n", x);
    return 0;
}

Output:

Do-while loop:
This prints once: x = 5
Final x = 6

🧠 Test Your Knowledge

What's the main advantage of do-while over while loop?