C++ While Loop

While loop in C++ is the simplest loop. It executed its statements repeatedly until the given condition remains true.  As the condition becomes false the while loop will be terminated and control goes to the statements after the while loop.

Syntax: while loop in C++

While (condition)
{
Statements;
}

Working: while loop in C++

In a while loop, first of all, the condition is evaluated. If the condition is true, the control is transferred inside the body of the while loop and executes all statements inside it.  After that, the control again moves to the beginning of the while loop and evaluates the condition again. This looping process continues until the condition remains true.  When the condition becomes false, the loop is terminated and control shifted to the statements followed by the while loop.

Flow Chart: While loop

Example: While loop in C++

//while loop in C++
#include <iostream>  
using namespace std;  
int main()  
{  
  int i = 0;
while (i < 10) {
  cout <<"Hello World: "<< i <<endl;
  i++;
}

return 0;
} 

Output

Hello World: 0
Hello World: 1
Hello World: 2
Hello World: 3
Hello World: 4
Hello World: 5
Hello World: 6
Hello World: 7
Hello World: 8
Hello World: 9

Leave a Reply