Back to course

Looping Structures: The 'do-while' loop

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 18: Looping Structures: The do-while Loop

The do-while loop is similar to while, but it guarantees that the loop body executes at least once, regardless of the initial condition.

do-while Loop Syntax

c do { // Code block to be executed } while (condition); // Note: Semicolon after the while condition is required!

How it Works (Exit-Controlled Loop)

  1. The code inside the do block executes immediately.
  2. After the first execution, the while (condition) is checked.
  3. If the condition is True, the loop repeats; otherwise, it terminates.

Example: Menu Input Validation

A common use case is forcing user input until a valid choice is made.

c #include <stdio.h>

int main() { int choice;

do {
    printf("1. Start | 2. Options | 3. Exit\n");
    printf("Enter choice (1-3): ");
    scanf("%d", &choice);
} while (choice < 1 || choice > 3);

printf("Valid choice selected: %d\n", choice);
return 0;

}

Comparison: while vs. do-while

Featurewhiledo-while
ControlEntry-controlled (check before execution)Exit-controlled (check after execution)
Minimum ExecutionZero timesAlways at least one time
SemicolonNo semicolon after while (...)Semicolon required after while (condition);