Website For Developers

Do While Loop in C++



Loops are the iterative structure that means they repeats a statement or a set of statements for a several times.
There are three types of loops in C++:
1) for loop
2) while loop
3) do while loop


do while loop

• do while loop in C++ is a same statement as while loops.
• The difference between them is in while loop the condition comes first before the statement but do-while condition comes after the statements.
• do keyword indicates the beginning of the loop.
• It keep iterates the statements and keep execute them until the condition is false.
• Number of iterations are not fixed.

Syntax

do {
  //Statements in the loop body
}
while (condition);


do while loop in C++ example

#include<iostream>
#include<conio.h>
using namespace std;
int main() {

  int counter = 1;
  do {
    cout<< "Counter Value: "<< counter<< endl;
    counter++;
  }
  while(counter<=5);
  getch();
  return 0;
}

Output

Counter Value: 1
Counter Value: 2
Counter Value: 3
Counter Value: 4
Counter Value: 5


C++ program to display the square roots of the first 10 even positive numbers

#include<iostream>
#include<conio.h>
using namespace std;
int main() {

  int i = 1;
  do {
    if (i%2 == 0) {
      cout<<"Square of "<< i<<" is: "<< i*i<< endl;
    }
    i++;
  }
  while(i<20);
  getch();
  return 0;
}

Output

Square of 0 is: 0
Square of 2 is: 4
Square of 4 is: 16
Square of 6 is: 36
Square of 8 is: 64
Square of 10 is: 100
Square of 12 is: 144
Square of 14 is: 196
Square of 16 is: 256
Square of 18 is: 324

Difference between for loop, while loop, do while loop

for loop while loop do while loop
Number of iterations are fixed Number of iterations are not fixed Number of iterations are not fixed
Condition comes before the loop body Condition comes before the loop body Condition comes after the loop body
Entry controlled loop Entry controlled loop Exit controlled loop