C++ do while Loop

In this lesson, we will learn about the C++ do-while loop with a few examples to better understand the topic.


C++ Do-while Loop

The basic syntax of the do-while loop is:

Basic syntax

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

The ‘do..while’ body is executed at least once before the condition is tested, distinguishing it from the while loop in one vital way.

In the basic syntax of the do while loop,

  • The loop’s body is first carried out by entering through do statement. The condition is then assessed.
  • The body of the loop within the do statement is repeated execution if the condition evaluates to true. A second assessment of the situation is made.
  • The body of the loop within the do statement is repeated execution if the condition evaluates to true.
  • Until the condition is evaluated as false, this process keeps going. The loop then ends.

Example

//Program prints 3 integers
#include <iostream>

using namespace std;
int main() {
  int number = 3;
  do {
    cout << number << " ";
    number--;
  }
  while (number >= 1);
  return 0;
}

Output

3 2 1

In this case, the do..while loop continues until the number >1. The loop ends when the value is 0.

That’s how the program performs

VariantVariable Updatenumber >= 1Action
1stnumber = 3True3 is printed. The number is decreased to 3.
2ndnumber = 2True2 is printed. The number is decreased to 2.
3rdnumber = 1TrueOne is printed. The number is decreased to 1.
4thnumber = 0falseProgram terminated

This concludes the C++ do while loop lesson. The next lesson will teach about the break Statement in C++.