03. The Do-While Loop & Guaranteed Execution

🟢 Difficulty: Beginner | Exit-Gated Iteration, Trailing Semicolons & Menu Systems

📖 Definition

A do-while loop is an exit-controlled iterative control structure in C. Unlike for and while loops, a do-while loop evaluates its condition expression at the bottom of the loop, guaranteeing that the loop body executes at least once regardless of whether the condition is true or false.

🎯 Why It Is Used

  • Interactive Menu Loops: Displaying an interactive console menu first, accepting user input, and then checking if the user chose to exit.
  • Guaranteed Initial Prompting: Prompting for user input before performing initial validation.

⚙️ How It Works

Execution enters the do { ... } block immediately. After completing the block, C evaluates the condition in while (condition);. If non-zero (true), control jumps back to the top of do. If zero (false), the loop terminates.

📝 Syntax

do {
    // Loop body statements (Guaranteed to execute AT LEAST ONCE)
} while (condition_expression); // CRITICAL: Trailing semicolon is MANDATORY!

🔀 Loop Type Comparison

Loop Type Control Gate Type Minimum Executions Best Use Case
forEntry-Controlled0 TimesFixed counter iteration (e.g. arrays)
whileEntry-Controlled0 TimesEvent-driven or stream-driven reading
do-whileExit-Controlled1 TimeInteractive menus & input re-prompting

🌱 Beginner Example: Simple Counter

#include <stdio.h>

int main(void) {
    int count = 1;

    do {
        printf("Pass %d executed\n", count);
        count++;
    } while (count <= 3);
    return 0;
}

🌼 Intermediate Example: Re-prompting for Input Until Valid

#include <stdio.h>

int main(void) {
    int age;

    // do-while ensures user is prompted AT LEAST ONCE
    do {
        printf("Please enter a valid age (1 - 120): ");
        scanf("%d", &age);
    } while (age < 1 || age > 120);

    printf("Age recorded successfully: %d years old.\n", age);
    return 0;
}

🌲 Advanced Example: Interactive Console Menu System

#include <stdio.h>

void display_menu(void) {
    puts("\n=== DATABASE CONTROL MENU ===");
    puts("1. View All Records");
    puts("2. Add New Record");
    puts("3. Delete Record");
    puts("4. Exit Application");
    printf("Enter choice (1-4): ");
}

int main(void) {
    int choice;

    do {
        display_menu();
        if (scanf("%d", &choice) != 1) {
            puts("Invalid choice format!");
            break;
        }

        switch (choice) {
            case 1: puts("Action: Fetching records..."); break;
            case 2: puts("Action: Record added."); break;
            case 3: puts("Action: Record deleted."); break;
            case 4: puts("Exiting database system. Goodbye!"); break;
            default: puts("Error: Choice out of range (1-4). Try again."); break;
        }
    } while (choice != 4);

    return 0;
}

🔍 Line-by-Line Explanation

  • do { ... } while (choice != 4);: Executes the menu display and action switch, repeating until the user selects option 4 (Exit).
  • while (age < 1 || age > 120);: Re-prompts the user as long as the entered age is invalid.

💻 Expected Terminal Output

=== DATABASE CONTROL MENU ===
1. View All Records
2. Add New Record
3. Delete Record
4. Exit Application
Enter choice (1-4): 1
Action: Fetching records...

=== DATABASE CONTROL MENU ===
1. View All Records
2. Add New Record
3. Delete Record
4. Exit Application
Enter choice (1-4): 4
Exiting database system. Goodbye!

⚠️ Common Mistakes & Pitfalls

  • Forgetting the Trailing Semicolon ;: Omitting the trailing semicolon in while (condition); causes a compilation syntax error.
  • Confusing Entry and Exit Behavior: Using do-while when a loop should not run at all for empty datasets.

📌 Important Rules & Limitations

  • A do-while loop always runs its body at least once.
  • The trailing semicolon after while (condition); is mandatory in C syntax.

🌐 Multilingual Explanation: English

A do-while loop checks its condition at the end of the loop, guaranteeing that the body executes at least once. It requires a mandatory trailing semicolon after while (condition);.

🌐 Multilingual Explanation: Hindi (Roman Script)

do-while loop mein condition aakhri mein check hoti hai, isliye iska code kam se kam 1 baar zaroor chalega. Aakhri mein while (condition); ke baad semicolon ; lagana zaroori hai.

🌐 Multilingual Explanation: Marathi (Roman Script)

do-while loop madhye condition shevati check hoti. Mhanun ha loop kaman 1 vela nakki chaalto. Shevati while (condition); nantar semicolon dhyava lagto.

❓ Practice Questions

  1. Why does a do-while loop guarantee at least one execution pass?
  2. What happens if you forget the semicolon at the end of while (condition);?
  3. Why is do-while preferred over while for console menu loops?

🚀 Practical Coding Challenge

Write a C program named pin_verifier.c that uses a do-while loop to prompt a user for a 4-digit security PIN (e.g. 1234). Allow a maximum of 3 attempts, exiting early if the correct PIN is entered.

🧭 Navigation & Breadcrumbs

← Previous: 02. The While Loop | Module 07 Guide | Next: 04. Nested Loops →