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

Using do-while for menu-driven programs

Using do-while for menu-driven programs

What you'll learn: How to ensure a user sees a menu at least once and keeps interacting with it until they choose to quit.

The "Action First" approach

In previous lessons, we looked at the while loop, which checks a condition before running any code. However, imagine you are designing a digital ATM. You wouldn't check if the user wants to quit before you’ve even shown them the "Withdraw" or "Deposit" buttons!

This is where the do-while loop shines. It is the "act first, ask questions later" tool of C programming. It guarantees that the block of code runs at least once, making it the industry standard for creating interactive menus.

Creating a persistent menu

A menu-driven program usually follows a simple rhythm:

  1. Display options.
  2. Get the user's choice.
  3. Perform the action.
  4. Repeat unless the user chose "Exit."

Because the menu must appear at least once for the user to even know what their options are, we wrap the logic in a do block. The while condition at the bottom keeps the loop spinning as long as the user hasn't typed the specific "quit" command.

A concrete example

Here is how you might structure a simple game lobby menu:

#include <stdio.h>

int main() {
    int choice;

    do {
        // 1. Display the menu
        printf("\n--- GAME LOBBY ---\n");
        printf("1. Start Game\n");
        printf("2. Settings\n");
        printf("3. Exit\n");
        printf("Enter your choice: ");
        
        // 2. Get user input
        scanf("%d", &choice);

        // 3. Respond to the input
        if (choice == 1) {
            printf("Loading world...\n");
        } else if (choice == 2) {
            printf("Opening settings...\n");
        } else if (choice != 3) {
            printf("Invalid option, try again.\n");
        }

    // 4. Repeat until the choice is 3 (Exit)
    } while (choice != 3);

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

Why this works

In the code above, the program enters the do block immediately. It doesn't care what the value of choice is yet. Once the user types a number, the while (choice != 3) at the bottom evaluates the situation. If the user typed 1 or 2, the condition is true (since 1 is not 3), and the loop restarts. Only when the user explicitly chooses 3 does the condition become false, breaking the loop and ending the program.

Key takeaway

Use a do-while loop for menus to ensure your interface displays immediately and remains active until the user decides to leave.