while loop in C++ language

  • while loop in C++ programming repeatedly executes a target statement as long as a given condition is true.
  • Its called a loop because control keeps looping back to the start of the statement until the test becomes false.
  • The loop iterates as long as the defined condition is true. When it ceases to be true and becomes false, control passes to the first line after the loop.

Syntax

while(condition)
  {
     statements(s);
  }

Flow Diagram

while loop in c++

Example

// endon0.cpp 
// demonstrates WHILE loop 
#include using namespace std; 

int main() 
{ 
  int n = 99; // make sure n isn’t initialized to 0 

  while( n != 0 ) // loop until n is 0 
    cin >> n; // read a number into n 
  cout << endl; 
  return 0; 
} 

Output

 1 
27 
33 
144 
9 
0