do while Loop

The do while loop in C++ is a looping statement that executes a block of code at least once before checking the condition. It is useful when the code must run one time regardless of the condition.

What is a do while Loop?

A do while loop is a control structure that:

  • Executes the loop body first
  • Checks the condition afterward
  • Repeats the loop while the condition is true

Unlike the while loop, the condition is checked after execution.

Syntax of do while Loop

do {
// code to execute
} while (condition);

How do while Loop Works

  1. The loop body executes first
  2. The condition is checked
  3. If the condition is true, the loop repeats
  4. If false, the loop stops

Example of do while Loop

#include <iostream>
using namespace std;

int main() {
int i = 1;

do {
cout << i << endl;
i++;
} while (i <= 5);

return 0;
}

Output

1
2
3
4
5

Example: User Input Program

#include <iostream>
using namespace std;

int main() {
int number;

do {
cout << "Enter a number (0 to stop): ";
cin >> number;

cout << "You entered: " << number << endl;

} while (number != 0);

return 0;
}

Difference Between while and do while Loop

while Loopdo while Loop
Condition checked firstCode executes first
May not execute at allExecutes at least once

Example Showing Difference

#include <iostream>
using namespace std;

int main() {
int i = 10;

do {
cout << "Executed once";
} while (i < 5);

return 0;
}

Even though the condition is false, the loop runs once.

Infinite do while Loop

do {
cout << "Infinite Loop";
} while (true);

Use infinite loops carefully.

Why do while Loop is Important

The do while loop is important because it:

  • Ensures code executes at least once
  • Is useful for menu-driven programs
  • Handles user input efficiently
  • Simplifies repetitive tasks
  • Supports condition-based repetition

Real-Life Example

Think of entering a password:

  • You must enter it at least once
  • The system checks if it is correct afterward
  • If incorrect, it asks again

This is how a do while loop works.

Conclusion

The do while loop in C++ is a useful looping structure when code needs to execute at least once before checking a condition. It is commonly used in menus, input validation, and interactive applications.

Home » C++ Fundamentals (Beginner Level) > Loops > do while Loop