How to Use Do While Loop in C++: Syntax and Examples
do while loop executes the code block first and then checks the condition to decide if it should repeat. It guarantees the loop runs at least once because the condition is checked after the code inside the loop.Syntax
The do while loop syntax in C++ consists of the do keyword followed by a block of code inside curly braces, and then the while keyword with a condition in parentheses. The loop runs the code block once before checking the condition. If the condition is true, it repeats the block; if false, it stops.
- do: starts the loop block
- code block: statements to execute
- while(condition): checks condition after running the block
- ;: semicolon ends the loop statement
do {
// code to execute
} while (condition);Example
This example shows a do while loop that prints numbers from 1 to 5. It runs the print statement first, then checks if the number is less than or equal to 5 to continue.
#include <iostream> int main() { int i = 1; do { std::cout << i << std::endl; i++; } while (i <= 5); return 0; }
Common Pitfalls
One common mistake is forgetting the semicolon ; after the while condition, which causes a syntax error. Another is using a condition that never becomes false, causing an infinite loop. Also, confusing do while with while loops can lead to unexpected behavior because do while always runs the code block at least once.
/* Wrong: Missing semicolon after while condition */ do { // some code } while (false) // <-- missing semicolon here /* Correct: Semicolon included */ do { // some code } while (false);
Quick Reference
- Use do while when you want the code to run at least once.
- Always end the
whilecondition with a semicolon. - Check your condition carefully to avoid infinite loops.
- Use braces
{ }even for single statements for clarity.