C++ do while Loop

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

C++ do-while Loop explained

The do-while loop is another type of loops in C++. It’s similar to the while loop. However, it executes the loop body before evaluating the condition/expression. So, a do-while loop will iterate at least for one time, regardless of the condition.


Syntax of the do-while loop

do {
  // code block to be executed while condition is true
}
while (condition);

Flowchart


Example I of the do-while loop in C++

#include <iostream>

using namespace std;
int main() {
  int num = 0;

  do {
    cout << num << endl;
    num++;
  }
  while (num < 5);
  return 0;
}

Output

0
1
2
3
4


Example II of the do-while loop in C++

#include <iostream>

using namespace std;
int main() {
  // declare an array
  string languages[4] = {
    "C++",
    "C",
    "Python",
    "Java"
  };
  // get the size of the array
  int arrSize = sizeof(languages) / sizeof(languages[0]);
  int i = 0;
  // loop through array element
  do {
    cout << languages[i] << "\n";
    i++;
  }
  while (i < arrSize);
}

Output

C++
C
Python
Java


Difference between while and do-while loops

whiledo-while
It evaluates the expression/condition before the statement is executed.It executes the statement before the expression/condition is evaluated.
No semicolon is required at the end of the condition
while(condition)
A semicolon is required at the end of the condition
while(condition);
Possible to have zero iteration if the condition is false initially.Should have at least one iteration regardless of the condition.
The variable in the condition/expression should be initialized before the loop.The variable in the condition/expression may be initialized before or within the loop body.
A single statement requires not curly brackets.Curly brackets are always required.

Points to remember

  • do-while loop executes the loop body before evaluating the condition/expression.
  • In do-while loops, the condition is always at the end of the loop.
  • A do-while loop will iterate at least for one time.
Back to: Learn C++ Programming > Control Statements in C++

Leave a Reply

Your email address will not be published. Required fields are marked *