0
0
CppHow-ToBeginner · 3 min read

How to Use Do While Loop in C++: Syntax and Examples

In C++, a 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
cpp
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.

cpp
#include <iostream>

int main() {
    int i = 1;
    do {
        std::cout << i << std::endl;
        i++;
    } while (i <= 5);
    return 0;
}
Output
1 2 3 4 5
⚠️

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.

cpp
/* 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 while condition with a semicolon.
  • Check your condition carefully to avoid infinite loops.
  • Use braces { } even for single statements for clarity.

Key Takeaways

The do while loop runs the code block first, then checks the condition to repeat.
Always include a semicolon after the while(condition) statement.
Use do while when you need the loop to execute at least once.
Be careful with the loop condition to avoid infinite loops.
Braces improve readability even for single statements inside the loop.