Introduction
The do-while loop is a post-test loop that executes a block of code at least once before checking the condition. Unlike while loops that check the condition before executing, do-while loops guarantee that the loop body executes at least one time, making them ideal for situations where you need the code to run first and then decide whether to repeat.
This loop structure is particularly useful for menu systems, input validation where you need at least one attempt, and scenarios where the initial execution is mandatory regardless of the condition.
Key Concepts
Post-Test Loop: Condition is checked after executing the loop body Guaranteed Execution: Loop body always executes at least once Exit-Controlled: The loop control is at the bottom of the loop Condition-Based Repetition: Continues based on a boolean condition
Syntax
do {
// Code to be executed
// Loop body
} while (condition);
Note: The semicolon after while is mandatory in do-while loops.
Basic Example
#include <stdio.h>
int main() {
int count = 1;
do {
printf("Count: %d\n", count);
count++;
} while (count <= 5);
return 0;
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Do-While vs While Loop
Key Differences
// While loop - may not execute at all
int x = 10;
while (x < 5) {
printf("This will not print\n");
x++;
}
// Do-while loop - executes at least once
int y = 10;
do {
printf("This will print once\n");
y++;
} while (y < 5);
When to Use Each
Use do-while when:
- You need the code to execute at least once
- Implementing menu systems
- Input validation scenarios
- User interaction loops
Use while when:
- The loop may not need to execute at all
- Processing data where initial condition check is important
Common Applications
Menu System
#include <stdio.h>
int main() {
int choice;
do {
printf("\n=== MENU ===\n");
printf("1. View Profile\n");
printf("2. Edit Profile\n");
printf("3. Settings\n");
printf("4. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Viewing profile...\n");
break;
case 2:
printf("Editing profile...\n");
break;
case 3:
printf("Opening settings...\n");
break;
case 4:
printf("Goodbye!\n");
break;
default:
printf("Invalid choice! Try again.\n");
}
} while (choice != 4);
return 0;
}
Input Validation
#include <stdio.h>
int main() {
int age;
do {
printf("Enter your age (1-120): ");
scanf("%d", &age);
if (age < 1 || age > 120) {
printf("Invalid age! Please try again.\n");
}
} while (age < 1 || age > 120);
printf("Your age is: %d\n", age);
return 0;
}
Password Verification
#include <stdio.h>
#include <string.h>
int main() {
char password[20];
char correct_password[] = "secure123";
do {
printf("Enter password: ");
scanf("%s", password);
if (strcmp(password, correct_password) != 0) {
printf("Incorrect password! Try again.\n");
}
} while (strcmp(password, correct_password) != 0);
printf("Access granted!\n");
return 0;
}
Practical Examples
Number Guessing Game
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
int secret = rand() % 100 + 1;
int guess, attempts = 0;
printf("Guess the number between 1-100!\n");
do {
printf("Enter your guess: ");
scanf("%d", &guess);
attempts++;
if (guess < secret) {
printf("Too low!\n");
} else if (guess > secret) {
printf("Too high!\n");
} else {
printf("Correct! You got it in %d attempts!\n", attempts);
}
} while (guess != secret);
return 0;
}
Sum Calculator
#include <stdio.h>
int main() {
int number, sum = 0;
char choice;
do {
printf("Enter a number: ");
scanf("%d", &number);
sum += number;
printf("Current sum: %d\n", sum);
printf("Add another number? (y/n): ");
scanf(" %c", &choice);
} while (choice == 'y' || choice == 'Y');
printf("Final sum: %d\n", sum);
return 0;
}
Simple ATM System
#include <stdio.h>
int main() {
float balance = 1000.0;
int choice;
float amount;
do {
printf("\n=== ATM SYSTEM ===\n");
printf("Balance: $%.2f\n", balance);
printf("1. Withdraw\n");
printf("2. Deposit\n");
printf("3. Check Balance\n");
printf("4. Exit\n");
printf("Choice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Enter withdrawal amount: $");
scanf("%f", &amount);
if (amount <= balance) {
balance -= amount;
printf("Withdrawal successful!\n");
} else {
printf("Insufficient funds!\n");
}
break;
case 2:
printf("Enter deposit amount: $");
scanf("%f", &amount);
balance += amount;
printf("Deposit successful!\n");
break;
case 3:
printf("Current balance: $%.2f\n", balance);
break;
case 4:
printf("Thank you for using ATM!\n");
break;
default:
printf("Invalid option!\n");
}
} while (choice != 4);
return 0;
}
Important Points
- Semicolon Required: Always include semicolon after while condition
- At Least One Execution: Body always executes minimum once
- Condition Placement: Condition is checked at the end of the loop
- Loop Variables: Ensure loop control variables are properly updated
- Infinite Loops: Make sure condition can eventually become false
Common Mistakes
Missing Semicolon
// Wrong - missing semicolon
do {
printf("Hello\n");
} while (condition) // Error: missing semicolon
// Correct
do {
printf("Hello\n");
} while (condition);
Infinite Loop
// Wrong - infinite loop
int i = 1;
do {
printf("%d\n", i);
// Missing i++ or condition never becomes false
} while (i <= 5);
// Correct
int i = 1;
do {
printf("%d\n", i);
i++; // Update loop variable
} while (i <= 5);
Loop Control Statements
Break Statement
#include <stdio.h>
int main() {
int num;
do {
printf("Enter a positive number (0 to exit): ");
scanf("%d", &num);
if (num == 0) {
break; // Exit loop immediately
}
if (num < 0) {
printf("Please enter positive numbers only!\n");
continue; // Skip to condition check
}
printf("You entered: %d\n", num);
} while (1); // Infinite loop, controlled by break
printf("Goodbye!\n");
return 0;
}
Nested Do-While Loops
#include <stdio.h>
int main() {
int i = 1;
do {
printf("Outer loop: %d\n", i);
int j = 1;
do {
printf(" Inner loop: %d\n", j);
j++;
} while (j <= 2);
i++;
} while (i <= 3);
return 0;
}
Summary
The do-while loop is a post-test loop that guarantees at least one execution of the loop body before checking the condition. It’s particularly useful for menu systems, input validation, and scenarios where initial execution is mandatory. Key differences from while loops include the guaranteed first execution and condition checking at the end. Common applications include user interaction systems, validation loops, and game mechanics. Important considerations include proper semicolon placement after the while condition, ensuring loop control variables are updated, and avoiding infinite loops. The do-while loop provides a clean solution for situations where you need to “do something first, then check if you should repeat it.”
Part of BCA Programming with C Course (UGCOA22J201)