Back to C++
2026-03-016 min read

Do/While Loop (C++)

Learn Do/While Loop (C++) step by step with clear examples and exercises.

Title: Mastering C++ Do/While Loop: A full guide for Programmers

Why This Matters

In programming, loops are essential to automate repetitive tasks. While for and while loops are commonly used, the do/while loop has a unique behavior that makes it indispensable in certain scenarios. Understanding how to use the do/while loop effectively can help you write more efficient code, solve complex problems, and avoid common pitfalls. This lesson will delve into the core concepts of C++'s do/while loop, providing practical examples, common mistakes, practice questions, and answers to frequently asked questions.

Prerequisites

Before diving into the do/while loop, it is essential to have a solid understanding of basic C++ syntax, variables, data types, and control structures such as if, else, and simple loops like for and while. Familiarity with the concept of pre- and post-conditions will also be beneficial. It's important to review these topics if you are not confident in your understanding.

Core Concept

The do/while loop is a control structure that executes a block of code repeatedly until a specified condition becomes false. Unlike the while loop, which checks the condition before entering the loop body, the do/while loop first executes the loop body and then checks the condition. This means that the loop body will always execute at least once, even if the condition is initially false.

The syntax for a do/while loop in C++ is as follows:

do {
// loop body
} while (condition);

In this structure, the code within the curly braces ({}) represents the loop body, and the condition following the while keyword determines when the loop will terminate. The semicolon at the end of the while statement is crucial—it signals the end of the line and allows the compiler to correctly interpret the syntax.

Example: Counting from 1 to 5 using a do/while loop

#include <iostream>

int main() {
int count = 1;
do {
std::cout << count << std::endl;
++count;
} while (count <= 5);

return 0;
}

In this example, the loop body consists of two lines: printing the current count and incrementing it by one. The do/while loop ensures that the initial value of count (1) is printed before the condition (count <= 5) is checked. This results in the output:

1
2
3
4
5

Example: Reading user input and calculating the sum of non-zero numbers using a do/while loop

#include <iostream>
#include <vector>

int main() {
std::vector<int> numbers;
int input;

do {
std::cout << "Enter a number (or leave empty line to quit): ";
std::cin >> input;

if (input != 0) {
numbers.push_back(input);
}
} while (std::cin);

int sum = 0;
for (const auto& number : numbers) {
if (number != 0) {
sum += number;
}
}

std::cout << "The sum of non-zero numbers is: " << sum << std::endl;

return 0;
}

In this example, the do/while loop reads user input and stores it in a vector. The condition for the loop termination is the end of the input stream (std::cin). Inside the loop, an if statement checks whether the entered number is non-zero before adding it to the vector. After the loop, a for loop iterates through the vector, calculating the sum of all non-zero numbers.

Common Mistakes

  1. ### Forgetting the semicolon after the while condition
do {
// code
} while (condition)

Instead, remember to include the semicolon:

do {
// code
} while (condition);
  1. ### Neglecting to initialize loop variables before entering the loop body
int count = 0;
do {
++count;
} while (count < 10);

This will result in an infinite loop, as count starts at 0 and never reaches 10. Initialize the variable before entering the loop body:

int count = 1;
do {
++count;
} while (count <= 10);
  1. ### Assuming the loop body will not execute if the initial condition is false
int count = 10;
do {
std::cout << count << std::endl;
--count;
} while (count > 0);

This will print nothing, as the loop body does not execute when count is initially greater than 0. To ensure that the loop body executes at least once, move the initialization of count inside the loop:

do {
int count = 1;
std::cout << count << std::endl;
--count;
} while (--count > 0);

Subheadings under Common Mistakes:

  • Forgetting the semicolon after the while condition
  • Neglecting to initialize loop variables before entering the loop body
  • Assuming the loop body will not execute if the initial condition is false

Worked Example

Example: Guessing Game using a do/while loop

#include <iostream>
#include <ctime>
#include <cstdlib>

int main() {
srand(time(0)); // Seed the random number generator
int secretNumber = rand() % 100 + 1; // Generate a secret number between 1 and 100
int guess;
bool found = false;

do {
std::cout << "Enter your guess: ";
std::cin >> guess;

if (guess > secretNumber) {
std::cout << "Too high! Try again.\n";
} else if (guess < secretNumber) {
std::cout << "Too low! Try again.\n";
}
} while (!found && guess != secretNumber);

if (found) {
std::cout << "Congratulations! You found the number.\n";
} else {
std::cout << "You didn't find the number. The secret number was: " << secretNumber << "\n";
}

return 0;
}

In this example, a do/while loop is used to create a simple guessing game where the user tries to guess a randomly generated number between 1 and 100. The loop continues until the user correctly guesses the secret number or the program determines that the user has not found the number (found flag is set to true).

Practice Questions

  1. Write a program that asks the user for their name and age, and then prints a personalized greeting with their name and age. Use a do/while loop to ensure that the user enters valid input (i.e., a non-empty string for their name and a positive integer for their age).
  1. Write a program that calculates the factorial of a number entered by the user using a do/while loop. The program should continue asking for input until the user enters 0 or a negative number.
  1. Modify the guessing game example to include three attempts for the user to guess the secret number. If the user doesn't find the number within three attempts, print "You didn't find the number. The secret number was: [secret number]."

FAQ

### Why use a do/while loop instead of a while loop?

A do/while loop ensures that the loop body executes at least once, even if the initial condition is false. This can be useful in scenarios where you want to execute some setup code before checking the condition or when dealing with user input where an empty or invalid initial input might occur.

### Can I use a do/while loop for infinite loops?

Yes, but it's generally better practice to use a traditional while (true) loop for infinite loops, as the do/while loop will still execute the loop body once before checking the condition. An infinite loop with a do/while can be created by setting the initial condition to true and not updating it within the loop body.

### What happens if I forget the semicolon after the while condition in a do/while loop?

If you forget the semicolon, the compiler will interpret the do/while loop as a for loop, which can lead to unexpected behavior and errors. Always include the semicolon after the while condition to ensure proper syntax.

Subheadings under FAQ:

  • Why use a do/while loop instead of a while loop?
  • Can I use a do/while loop for infinite loops?
  • What happens if I forget the semicolon after the while condition in a do/while loop?
Do/While Loop (C++) | C++ | XQA Learn