While Loop:

Loop executes the same block of code again and again until the given condition remains true. We use while loop when we do not know the number of iterations. We know the condition and variable value and in some cases variable value is given by the user.


Steps:

  1. Initialize a variable.
  2. Check the condition.
  3. Change the value of the variable.
//initialize variable
while(check condition){
    //code
    //change value of variable
}

Example:

The following code is using while loop to print name ten times.

while.cpp
#include <iostream>
using namespace std;

int main(){
    int a = 10;
    while(i>0){
        cout<<"My name is John"<<endl;
        a--;
    }
    return 0;
}

This will print name 10 times.

Program to print couting from 1 to 5:

In the following code, we will print the numbers from one to five times.

while.cpp
#include <iostream>
using namespace std;

int main(){
    int i = 0;
    do{
        cout<<i<<endl;
        i++;
    }
    while(i < 5);
    return 0;
}

Note : If we write true in parenthesis, the while loop will become infinite. You can use ctrl + c on your keyboard to stop an infinite loop.


Do-While Loop:

The is one major difference between while and do while loop. In do while loop, first iteration is done without checking the condition. After first iteration, condition is checked and if it is true second iteration is done and this continues until the condition is true.

do-while.cpp
#include <iostream>
using namespace std;

int main(){
    int a = 5;
    do{
        cout<<"My name is John\n";
        a--;
    }while(a>0);
    return 0;
}

This code will execute one time, no matter the condition is true or false. But after the first iteration, it will check the condition. If the condition is true, the loop will run. If the given condition is false, the loop will be terminated and the control will move out of the loop. You must make sure that after each iteration variable value must be changed.