while loop in c++


  • A 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.
  • The reserved word while begins the while statement.
  • The Boolean expression condition determines whether the body will be (or will continue to be) executed. The expression must be enclosed within parentheses as shown.
  • The statement is the statement to be executed while the Boolean expression is true. The statement makes up the body of the while statement.

Syntax

    while(condition)
      {
         statements(s);
      }

Flow Diagram

    while-loop statement in c++ language

Example

    #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