C++ while Loop

A while loop is another kind of loop control structure. The loop has initial condition and a test condition to pass before the actual loop body starts. The loop is incremented or decremented inside of the loop body.

The general structure of while loop is given below.

initial expression;

while( test condition)

{

     do something;
     increment or decrement loop;
}

The initial expression is a simple assignment where a loop starts with 0 or 1. The test condition can be an expression, return from a function, or a constant. The loop is incremented or decremented inside the body of the loop.

You can note the similarity between while loop and for loop, both contains 3 expressions. However, with while loop the initialization happens before the loop body starts.

Graphical Representation of while loop

A graphical representation is helpful when you create a flowchart of your C++ program. Here is the graphical representation of while loop.

while Loop Diagram
while Loop Diagram

Example Program:


//While loop

#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    //variable declaration and initialization
    
    int number,i;
    int sum = 0;
    
    //read values and computing total 
    
    for(i = 0;i<5; i++)
    {
          cout << "Enter Number:";
          cin >> number;
          
          sum = sum + number;

    }
    
    //printing output 
    
    cout << "Sum = " << " " << sum << endl;
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

Output:

Enter Number:23
Enter Number:55
Enter Number:66
Enter Number:67
Enter Number:76
Sum =  287

Please support us by disabling your adblocker or whitelist this site from your adblocker. Thanks!

turn of adblocker imag