What is the difference between while and do-while loop in C++?

Overview

In C, we use loops to execute the specified code as long as the condition becomes true. We use the while loop to run the code block if the specified condition is true.

Code

In this example, the code in the loop will run if the value of the variable i equals 10.

#include <iostream>
using namespace std;
int main() {
int i = 0;
while (i <= 10)
{
cout << i << endl;
i++;
}
return 0;
}

Do-while loop

The do-while loop is the form of the while loop. The code in the loop will execute once before checking if the condition is true or not. Then the code will execute as long as the condition is true.

Code

In this example, the code in the loop will execute at least once, whether the condition is true or false, because the code block is executed before the condition is checked.

#include <iostream>
using namespace std;
int main() {
int i = 0;
do {
cout << i <<endl;
i++;
}
while( i <= 10);
return 0;
}

Difference

The main difference between the while and do-while loop is given below

DIFFERENCE

While Loop

Do/While Loop

The block of code is executed as long as the specified condition becomes true.

The code in the loop will execute at least once, whether the condition is true or false.

Free Resources