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)
- The code inside the
doblock executes immediately. - After the first execution, the
while (condition)is checked. - 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
| Feature | while | do-while |
|---|---|---|
| Control | Entry-controlled (check before execution) | Exit-controlled (check after execution) |
| Minimum Execution | Zero times | Always at least one time |
| Semicolon | No semicolon after while (...) | Semicolon required after while (condition); |