C++ While loop

C++ While loop: The C++ while loop repeats the statement until the condition is true. In this loop, we do not know no. of loops in before like the for loop. So here the loop execution is terminated based on the test condition. So in while loops then it can be a single statement (or) a block of statements. In such a way the condition can be any expression (or) a non-zero value.

C++ While loop – Syntax, Examples

It basically targets the statement as long as the condition is true. As we already said before that loop consists of three statements. i.e. initialization expression, test expression and update expression.

Syntax:

initialization expression;
while (test_expression)
{
// statements
update_expression;
}

c++ while loop flow chart

C++ While loop Example 1:

#include <iostream> 
using namespace std; 
int main() 
{ 
// initialization expression 
    int i = 1; 
 // test expression 
   while (i < 6) 
   { 
      cout << "Wow freshersnow\n"; 
//update expression 
      i++; 
     } 
return 0; 
}

Output:

Wow freshersnow
Wow freshersnow
Wow freshersnow
Wow freshersnow
Wow freshersnow

Example 2:

#include <iostream>
 using namespace std;
int main () {
int x = 10;//local variable
while(x < 20){ //while loop execution
  cout<<"value of x:"<<x<<endl;
   x++;
 }
 return 0;
}

Output:

value of x: 10
value of x: 11
value of x: 12
value of x: 13
value of x: 14
value of x: 15
value of x: 16
value of x: 17
value of x: 18
value of x: 19