Among C's three loop structures (while, for, and do-while), the do-while loop holds a unique position—it's the only loop that guarantees at least one execution of the loop body before checking the condition. This "execute first, check later" behavior makes it ideal for situations where you need to perform an action at least once, such as displaying menus, processing user input, or validating data.
What is a Do-While Loop?
The do-while loop is a control flow statement that executes a block of code once, then repeatedly executes it as long as a given condition remains true. The key characteristic is that the condition is evaluated after the loop body, ensuring the body executes at least once.
Basic Syntax
do {
// Code to execute at least once
// This block runs, then condition is checked
} while (condition);
Important: Note the semicolon ; after the while condition—this is required and often a source of errors for beginners.
Simple Do-While Example
#include <stdio.h>
int main() {
int count = 1;
do {
printf("Count is: %d\n", count);
count++;
} while (count <= 5);
printf("Loop finished!\n");
return 0;
}
Output:
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Loop finished!
Key Difference: Do-While vs While
The critical distinction between do-while and while loops is when the condition is checked:
#include <stdio.h>
int main() {
int x = 10;
// While loop - checks first, then executes
printf("While loop with x = 10 (condition false initially):\n");
while (x < 5) {
printf("This will NOT print\n");
x++;
}
// Reset x
x = 10;
// Do-while loop - executes first, then checks
printf("\nDo-while loop with x = 10 (condition false initially):\n");
do {
printf("This prints ONCE even though condition is false\n");
} while (x < 5);
return 0;
}
Output:
While loop with x = 10 (condition false initially): Do-while loop with x = 10 (condition false initially): This prints ONCE even though condition is false
Practical Applications
1. Menu-Driven Programs
Do-while loops excel at creating interactive menus where the menu should display at least once:
#include <stdio.h>
int main() {
int choice;
do {
printf("\n=== MAIN MENU ===\n");
printf("1. Start Game\n");
printf("2. Load Game\n");
printf("3. Options\n");
printf("4. High Scores\n");
printf("5. Exit\n");
printf("Enter your choice (1-5): ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Starting game...\n");
break;
case 2:
printf("Loading game...\n");
break;
case 3:
printf("Options menu...\n");
break;
case 4:
printf("Displaying high scores...\n");
break;
case 5:
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 5);
printf("Goodbye!\n");
return 0;
}
2. Input Validation
When you need to repeatedly ask for input until it's valid, do-while ensures the prompt appears at least once:
#include <stdio.h>
int main() {
int age;
int valid;
do {
printf("Enter your age (1-120): ");
valid = scanf("%d", &age);
// Clear input buffer if invalid input
while (getchar() != '\n');
if (valid != 1 || age < 1 || age > 120) {
printf("Invalid input! Please enter a number between 1 and 120.\n");
valid = 0; // Set to 0 to repeat the loop
}
} while (!valid);
printf("Valid age entered: %d\n", age);
return 0;
}
3. Password Entry System
Do-while is perfect for password prompts that must appear at least once:
#include <stdio.h>
#include <string.h>
int main() {
char password[50];
const char *correctPassword = "secret123";
int attempts = 0;
const int MAX_ATTEMPTS = 3;
do {
printf("Enter password (attempt %d of %d): ", attempts + 1, MAX_ATTEMPTS);
scanf("%s", password);
attempts++;
if (strcmp(password, correctPassword) == 0) {
printf("Access granted!\n");
break;
} else {
printf("Incorrect password.\n");
}
} while (attempts < MAX_ATTEMPTS);
if (attempts >= MAX_ATTEMPTS && strcmp(password, correctPassword) != 0) {
printf("Too many failed attempts. Account locked.\n");
}
return 0;
}
4. Number Guessing Game
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int secret, guess;
int attempts = 0;
// Seed random number generator
srand(time(NULL));
secret = rand() % 100 + 1; // Random number between 1 and 100
printf("I'm thinking of a number between 1 and 100.\n");
do {
printf("Enter your guess: ");
scanf("%d", &guess);
attempts++;
if (guess < secret) {
printf("Too low! Try again.\n");
} else if (guess > secret) {
printf("Too high! Try again.\n");
}
} while (guess != secret);
printf("Congratulations! You guessed it in %d attempts.\n", attempts);
return 0;
}
5. Data Processing with Sentinel Value
Using a sentinel value to end data entry:
#include <stdio.h>
int main() {
int number;
int sum = 0;
int count = 0;
printf("Enter numbers to sum (enter -1 to stop):\n");
do {
printf("Number %d: ", count + 1);
scanf("%d", &number);
if (number != -1) {
sum += number;
count++;
}
} while (number != -1);
if (count > 0) {
printf("Sum of %d numbers: %d\n", count, sum);
printf("Average: %.2f\n", (float)sum / count);
} else {
printf("No numbers entered.\n");
}
return 0;
}
Nested Do-While Loops
Just like other loops, do-while loops can be nested:
#include <stdio.h>
int main() {
int i = 1, j;
do {
j = 1;
do {
printf("%d ", i * j);
j++;
} while (j <= 5);
printf("\n");
i++;
} while (i <= 5);
return 0;
}
Output:
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
Infinite Do-While Loops
Creating intentional infinite loops with do-while:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int randomNumber;
srand(time(NULL));
printf("Generating random numbers until we get 42...\n");
do {
randomNumber = rand() % 100;
printf("Generated: %d\n", randomNumber);
// Could add a break condition
if (randomNumber == 42) {
printf("Found the answer!\n");
break;
}
} while (1); // Infinite loop, but we break inside
return 0;
}
Common Pitfalls and Best Practices
1. Missing Semicolon
The most common mistake is forgetting the semicolon after the while condition:
// WRONG - missing semicolon
do {
printf("Hello\n");
} while (x < 5) // Missing semicolon!
// CORRECT
do {
printf("Hello\n");
} while (x < 5);
2. Infinite Loops
Accidentally creating infinite loops:
// WRONG - condition never becomes false
int x = 1;
do {
printf("%d\n", x);
// Missing x++ or x never changes!
} while (x < 10);
// CORRECT
int x = 1;
do {
printf("%d\n", x);
x++; // Increment ensures loop ends
} while (x < 10);
3. Scope of Variables
Variables declared inside the loop are recreated each iteration:
do {
int temp = 0; // Created and destroyed each iteration
temp += x;
printf("%d\n", temp);
} while (x++ < 5);
4. Braces for Single Statements
Even for single statements, using braces is recommended:
// Works but risky - adding more statements later breaks
do
printf("Hello\n");
while (x < 5);
// Safer - braces make intent clear
do {
printf("Hello\n");
} while (x < 5);
Performance Considerations
Do-while loops are generally as efficient as while loops. The main performance difference comes from the guaranteed first execution:
#include <stdio.h>
#include <time.h>
int main() {
int i;
clock_t start, end;
double cpu_time_used;
// While loop
start = clock();
i = 0;
while (i < 1000000) {
i++;
}
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("While loop time: %f seconds\n", cpu_time_used);
// Do-while loop (comparable performance)
start = clock();
i = 0;
do {
i++;
} while (i < 1000000);
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Do-while loop time: %f seconds\n", cpu_time_used);
return 0;
}
Choosing the Right Loop
| Scenario | Best Loop | Why |
|---|---|---|
| Loop must execute at least once | Do-while | Guarantees one execution |
| Loop may execute zero times | While | Checks condition first |
| Known number of iterations | For | Built-in counter |
| Menu-driven programs | Do-while | Menu shows at least once |
| Input validation | Do-while | Prompt appears at least once |
Advanced Example: ATM Simulation
#include <stdio.h>
int main() {
int choice;
double balance = 1000.0;
double amount;
printf("Welcome to ATM Simulator\n");
do {
printf("\n=== ATM MENU ===\n");
printf("1. Check Balance\n");
printf("2. Deposit\n");
printf("3. Withdraw\n");
printf("4. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Current balance: $%.2f\n", balance);
break;
case 2:
do {
printf("Enter deposit amount: $");
scanf("%lf", &amount);
if (amount <= 0) {
printf("Amount must be positive. Try again.\n");
}
} while (amount <= 0);
balance += amount;
printf("Deposit successful. New balance: $%.2f\n", balance);
break;
case 3:
do {
printf("Enter withdrawal amount: $");
scanf("%lf", &amount);
if (amount <= 0) {
printf("Amount must be positive. Try again.\n");
} else if (amount > balance) {
printf("Insufficient funds. Maximum withdrawal: $%.2f\n", balance);
}
} while (amount <= 0 || amount > balance);
balance -= amount;
printf("Withdrawal successful. New balance: $%.2f\n", balance);
break;
case 4:
printf("Thank you for using ATM. Goodbye!\n");
break;
default:
printf("Invalid choice! Please enter 1-4.\n");
}
} while (choice != 4);
return 0;
}
Common Interview Questions
Q: What's the output of this code?
int x = 0;
do {
printf("%d ", x);
x++;
} while (x < 0);
printf("Done");
A: 0 Done - The loop executes once (prints 0), then checks condition (0 < 0 is false) and exits.
Q: When would you use do-while instead of while?
A: Use do-while when you need the loop body to execute at least once, regardless of the condition. Common examples include menu displays, input validation, and initialization routines.
Conclusion
The do-while loop, with its unique "execute first, check later" behavior, fills an important niche in C programming. It's the tool of choice when you need guaranteed at least one execution of a block of code—a requirement that appears frequently in interactive programs, data validation, and user interfaces.
Key takeaways:
- Do-while guarantees at least one execution of the loop body
- Always remember the semicolon after the
whilecondition - Perfect for menus, input validation, and user prompts
- The condition is checked after each iteration
- Can be nested and combined with other control structures
Mastering the do-while loop expands your programming toolkit, giving you the ability to handle scenarios where other loops fall short. Whether you're building a simple menu or a complex validation system, the do-while loop provides the exact behavior you need for situations that require guaranteed first execution.