Coming Soon
This lesson is currently being developed
Do while statements
Learn post-test loops with do-while statements.
What to Expect
Comprehensive explanations with practical examples
Interactive coding exercises to practice concepts
Knowledge quiz to test your understanding
Step-by-step guidance for beginners
Development Status
Content is being carefully crafted to provide the best learning experience
Preview
Early Preview Content
This content is still being developed and may change before publication.
8.9 — Do while statements
In this lesson, you'll learn about do-while loops, understand how they differ from while loops, discover when they're most useful, and master this important variant of loop control.
What is a do-while loop?
A do-while loop is similar to a while loop, but with one crucial difference: it always executes the loop body at least once before checking the condition. The condition is evaluated at the end of each iteration.
Syntax:
do
{
// Code to execute at least once
// and repeatedly while condition is true
} while (condition); // Note the semicolon!
Do-while vs while loops
While loop (condition checked first)
#include <iostream>
int main()
{
int x = 10;
while (x < 5) // Condition is false initially
{
std::cout << "This will never print\n";
++x;
}
std::cout << "While loop finished\n";
return 0;
}
Output:
While loop finished
Do-while loop (condition checked after)
#include <iostream>
int main()
{
int x = 10;
do
{
std::cout << "This prints at least once: " << x << std::endl;
++x;
} while (x < 5); // Condition is false, but body already executed
std::cout << "Do-while loop finished\n";
return 0;
}
Output:
This prints at least once: 10
Do-while loop finished
Basic do-while examples
Example 1: Simple counting
#include <iostream>
int main()
{
int count = 1;
do
{
std::cout << "Count: " << count << std::endl;
++count;
} while (count <= 5);
return 0;
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Example 2: User input validation
#include <iostream>
int main()
{
int number;
do
{
std::cout << "Enter a positive number: ";
std::cin >> number;
if (number <= 0)
{
std::cout << "Error: Please enter a positive number!\n";
}
} while (number <= 0); // Keep asking until valid input
std::cout << "Thank you! You entered: " << number << std::endl;
return 0;
}
Sample Output:
Enter a positive number: -5
Error: Please enter a positive number!
Enter a positive number: 0
Error: Please enter a positive number!
Enter a positive number: 8
Thank you! You entered: 8
When to use do-while loops
Do-while loops are perfect when:
- You need the loop body to execute at least once
- You're validating user input
- You're implementing menu systems
- You're doing post-test loops (test after action)
Classic use case: Menu systems
#include <iostream>
int main()
{
int choice;
do
{
std::cout << "\n=== CALCULATOR MENU ===\n";
std::cout << "1. Add\n";
std::cout << "2. Subtract\n";
std::cout << "3. Multiply\n";
std::cout << "4. Divide\n";
std::cout << "5. Exit\n";
std::cout << "Choose an option: ";
std::cin >> choice;
if (choice >= 1 && choice <= 4)
{
double a, b;
std::cout << "Enter first number: ";
std::cin >> a;
std::cout << "Enter second number: ";
std::cin >> b;
switch (choice)
{
case 1:
std::cout << "Result: " << a << " + " << b << " = " << (a + b) << std::endl;
break;
case 2:
std::cout << "Result: " << a << " - " << b << " = " << (a - b) << std::endl;
break;
case 3:
std::cout << "Result: " << a << " * " << b << " = " << (a * b) << std::endl;
break;
case 4:
if (b != 0)
{
std::cout << "Result: " << a << " / " << b << " = " << (a / b) << std::endl;
}
else
{
std::cout << "Error: Division by zero!\n";
}
break;
}
}
else if (choice == 5)
{
std::cout << "Goodbye!\n";
}
else
{
std::cout << "Invalid choice! Please try again.\n";
}
} while (choice != 5); // Continue until user chooses to exit
return 0;
}
Another common pattern: "Play again?" loops
#include <iostream>
int main()
{
char playAgain;
do
{
std::cout << "\n=== NUMBER GUESSING GAME ===\n";
int secretNumber = 7; // In real game, this would be random
int guess;
int attempts = 0;
bool hasWon = false;
while (!hasWon && attempts < 3)
{
std::cout << "Guess a number between 1-10: ";
std::cin >> guess;
++attempts;
if (guess == secretNumber)
{
std::cout << "Congratulations! You won in " << attempts << " attempt(s)!\n";
hasWon = true;
}
else if (guess < secretNumber)
{
std::cout << "Too low!\n";
}
else
{
std::cout << "Too high!\n";
}
}
if (!hasWon)
{
std::cout << "Game over! The number was " << secretNumber << ".\n";
}
std::cout << "Play again? (y/n): ";
std::cin >> playAgain;
} while (playAgain == 'y' || playAgain == 'Y');
std::cout << "Thanks for playing!\n";
return 0;
}
Practical examples
Example 1: Password strength checker
#include <iostream>
#include <string>
bool isStrongPassword(const std::string& password)
{
if (password.length() < 8)
return false;
bool hasUpper = false, hasLower = false, hasDigit = false;
for (char c : password)
{
if (c >= 'A' && c <= 'Z') hasUpper = true;
if (c >= 'a' && c <= 'z') hasLower = true;
if (c >= '0' && c <= '9') hasDigit = true;
}
return hasUpper && hasLower && hasDigit;
}
int main()
{
std::string password;
do
{
std::cout << "Create a strong password: ";
std::cin >> password;
if (!isStrongPassword(password))
{
std::cout << "Password too weak! Requirements:\n";
std::cout << "- At least 8 characters\n";
std::cout << "- Contains uppercase letters\n";
std::cout << "- Contains lowercase letters\n";
std::cout << "- Contains numbers\n\n";
}
} while (!isStrongPassword(password));
std::cout << "Strong password created successfully!\n";
return 0;
}
Example 2: ATM PIN validation
#include <iostream>
int main()
{
const int correctPIN = 1234;
int enteredPIN;
int attempts = 0;
const int maxAttempts = 3;
bool accessGranted = false;
do
{
std::cout << "Enter your 4-digit PIN: ";
std::cin >> enteredPIN;
++attempts;
if (enteredPIN == correctPIN)
{
std::cout << "Access granted! Welcome!\n";
accessGranted = true;
}
else
{
std::cout << "Incorrect PIN. ";
std::cout << "Attempts remaining: " << (maxAttempts - attempts) << std::endl;
}
} while (!accessGranted && attempts < maxAttempts);
if (!accessGranted)
{
std::cout << "Too many failed attempts. Card blocked.\n";
}
return 0;
}
Sample Output:
Enter your 4-digit PIN: 1111
Incorrect PIN. Attempts remaining: 2
Enter your 4-digit PIN: 2222
Incorrect PIN. Attempts remaining: 1
Enter your 4-digit PIN: 1234
Access granted! Welcome!
Example 3: Dice rolling simulator
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
// Seed random number generator
std::srand(std::time(nullptr));
char rollAgain;
do
{
// Roll two dice
int die1 = (std::rand() % 6) + 1;
int die2 = (std::rand() % 6) + 1;
int total = die1 + die2;
std::cout << "\nRolling dice...\n";
std::cout << "Die 1: " << die1 << std::endl;
std::cout << "Die 2: " << die2 << std::endl;
std::cout << "Total: " << total << std::endl;
// Check for special combinations
if (die1 == die2)
{
std::cout << "DOUBLES! You rolled " << die1 << "'s!\n";
}
if (total == 7)
{
std::cout << "LUCKY SEVEN!\n";
}
else if (total == 11)
{
std::cout << "ELEVEN - Winner!\n";
}
std::cout << "Roll again? (y/n): ";
std::cin >> rollAgain;
} while (rollAgain == 'y' || rollAgain == 'Y');
std::cout << "Thanks for playing!\n";
return 0;
}
Do-while with different condition types
Using boolean variables
#include <iostream>
int main()
{
bool keepPlaying = true;
int score = 0;
do
{
int points;
std::cout << "Current score: " << score << std::endl;
std::cout << "Enter points earned (or -1 to quit): ";
std::cin >> points;
if (points == -1)
{
keepPlaying = false;
}
else
{
score += points;
}
} while (keepPlaying);
std::cout << "Final score: " << score << std::endl;
return 0;
}
Complex conditions
#include <iostream>
int main()
{
int lives = 3;
int score = 0;
char action;
do
{
std::cout << "\nLives: " << lives << " | Score: " << score << std::endl;
std::cout << "Action - (p)lay, (r)est, (q)uit: ";
std::cin >> action;
if (action == 'p')
{
// Simulate gameplay
bool success = (std::rand() % 2 == 0); // 50% chance of success
if (success)
{
score += 100;
std::cout << "Success! +100 points\n";
}
else
{
--lives;
std::cout << "Failed! Lost a life\n";
}
}
else if (action == 'r')
{
if (score >= 50)
{
score -= 50;
++lives;
std::cout << "Rested! Traded 50 points for 1 life\n";
}
else
{
std::cout << "Not enough points to rest\n";
}
}
} while (action != 'q' && lives > 0); // Continue until quit or no lives
if (lives == 0)
{
std::cout << "Game Over! Final score: " << score << std::endl;
}
else
{
std::cout << "Thanks for playing! Final score: " << score << std::endl;
}
return 0;
}
Common mistakes with do-while loops
Mistake 1: Forgetting the semicolon
// WRONG - Missing semicolon
do
{
std::cout << "Hello\n";
} while (condition) // ERROR: Missing semicolon!
// CORRECT
do
{
std::cout << "Hello\n";
} while (condition); // Semicolon required!
Mistake 2: Not updating the loop variable
#include <iostream>
int main()
{
int count = 1;
do
{
std::cout << "Count: " << count << std::endl;
// BUG: Forgot to increment count - infinite loop!
} while (count <= 5);
return 0; // Never reached
}
Mistake 3: Wrong condition logic
#include <iostream>
int main()
{
char choice;
do
{
std::cout << "Continue? (y/n): ";
std::cin >> choice;
} while (choice == 'y'); // BUG: Exits on 'y', continues on anything else!
// Should be:
// } while (choice != 'n' && choice != 'N');
return 0;
}
Do-while vs while: Choosing the right loop
Use do-while when:
- Loop body must execute at least once
- You're validating input
- You're showing a menu
- You're implementing "try again" logic
- You're doing post-condition testing
Use while when:
- Loop might not need to execute at all
- You're doing pre-condition testing
- The number of iterations is variable and could be zero
- You're processing data that might be empty
Example comparison:
#include <iostream>
int main()
{
// Scenario: Read positive numbers and sum them
// Using while loop
std::cout << "Using while loop:\n";
int sum1 = 0;
int number1;
std::cout << "Enter positive numbers (0 to stop): ";
std::cin >> number1;
while (number1 > 0)
{
sum1 += number1;
std::cout << "Enter next number (0 to stop): ";
std::cin >> number1;
}
std::cout << "Sum: " << sum1 << std::endl;
// Using do-while loop
std::cout << "\nUsing do-while loop:\n";
int sum2 = 0;
int number2;
do
{
std::cout << "Enter a positive number (0 to stop): ";
std::cin >> number2;
if (number2 > 0)
{
sum2 += number2;
}
} while (number2 > 0);
std::cout << "Sum: " << sum2 << std::endl;
return 0;
}
Best practices for do-while loops
1. Always include the semicolon
do
{
// Loop body
} while (condition); // Don't forget this semicolon!
2. Make the condition clear
// Good - clear intent
do
{
processUser();
std::cout << "Process another user? (y/n): ";
std::cin >> response;
} while (response == 'y' || response == 'Y');
// Less clear
do
{
processUser();
std::cout << "Continue? ";
std::cin >> response;
} while (response != 'n'); // What about 'N'? Or other characters?
3. Update loop variables properly
do
{
// Process data
++counter; // Update at consistent location
success = tryAgain();
} while (!success && counter < maxTries);
4. Use meaningful variable names
// Good
bool userWantsToContinue = true;
do
{
playGame();
userWantsToContinue = askPlayAgain();
} while (userWantsToContinue);
// Less descriptive
bool flag = true;
do
{
playGame();
flag = askPlayAgain();
} while (flag);
Summary
Do-while loops provide post-test repetition control:
Key characteristics:
- Body executes at least once before condition is tested
- Condition evaluated at the end of each iteration
- Perfect for input validation and menu systems
- Requires semicolon after the while condition
When to use do-while:
- Loop body must run at least once
- Input validation scenarios
- Menu-driven programs
- "Try again" logic
- Post-condition testing
Common patterns:
- User input validation
- Menu systems
- "Play again" games
- PIN/password verification
- Configuration wizards
Best practices:
- Don't forget the semicolon
- Make conditions clear and complete
- Update loop variables consistently
- Use descriptive variable names
- Consider user experience in prompts
Do-while loops are essential for creating user-friendly interactive programs where you need to guarantee at least one execution of the loop body.
Quiz
- How does a do-while loop differ from a while loop?
- When is the condition in a do-while loop evaluated?
- What happens if you forget the semicolon after a do-while loop?
- When should you use a do-while loop instead of a while loop?
- Can a do-while loop execute zero times?
Practice exercises
-
Input validator: Write a program that asks users to enter a number between 1 and 100, and keeps asking until they provide a valid input.
-
Simple quiz: Create a quiz program that asks questions and allows users to take the quiz again after seeing their score.
-
Unit converter: Build a unit conversion program with a menu that lets users convert between different units (temperature, distance, weight) and keeps running until they choose to exit.
-
Account balance simulator: Create a simple banking program that shows a balance and allows deposits, withdrawals, and balance checks, continuing until the user chooses to exit.
Explore More Courses
Discover other available courses while this lesson is being prepared.
Browse CoursesLesson Discussion
Share your thoughts and questions