Do-While Loop
The do-while loop is a special type of loop in C that guarantees the loop body executes at least once, regardless of the condition. Think of it like this: "Do something first, then check if you should continue doing it."
Syntax
do {
// Code to be executed
} while (condition);
Notice the semicolon (;) after the while statement - it's required!
How It Works
- Execute the code block first
- Check the condition after execution
- If the condition is
true, repeat from step 1 - If the condition is
false, exit the loop
Key Difference from While Loop
| While Loop | Do-While Loop |
|---|---|
| Checks condition before execution | Checks condition after execution |
| May execute 0 or more times | Always executes at least once |
Basic Example
#include <stdio.h>
int main() {
int count = 1;
do {
printf("Count: %d\n", count);
count++;
} while (count <= 3);
return 0;
}
Output:
Count: 1
Count: 2
Count: 3
Real-World Example: Menu System
Do-while loops are perfect for menu systems where you want to show the menu at least once:
#include <stdio.h>
int main() {
int choice;
do {
printf("\n=== MENU ===\n");
printf("1. Play Game\n");
printf("2. View Scores\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Starting game...\n");
break;
case 2:
printf("Displaying scores...\n");
break;
case 3:
printf("Goodbye!\n");
break;
default:
printf("Invalid choice! Try again.\n");
}
} while (choice != 3);
return 0;
}
Example: Input Validation
#include <stdio.h>
int main() {
int number;
do {
printf("Enter a positive number: ");
scanf("%d", &number);
if (number <= 0) {
printf("That's not positive! Try again.\n");
}
} while (number <= 0);
printf("Great! You entered: %d\n", number);
return 0;
}
When to Use Do-While Loop
✅ Use do-while when:
- You need the code to run at least once
- Creating menu systems
- Input validation scenarios
- Game loops that should run once before checking conditions
❌ Don't use do-while when:
- The loop might not need to execute at all
- You want to check the condition before the first execution
Common Pitfall
Remember the semicolon after while(condition)! This is a common mistake:
// ❌ Wrong - missing semicolon
do {
printf("Hello\n");
} while (condition) // Missing semicolon!
// ✅ Correct
do {
printf("Hello\n");
} while (condition); // Semicolon is required
The do-while loop is your go-to choice when you're certain that your code block needs to execute at least once before any condition checking takes place!