Cpp - Statement While Statement

Introduction

Loops performs a set of instructions repeatedly.

The set of instructions to be iterated is the loop body.

C++ offers three language elements to formulate iteration statements: while, do-while, and for.

The while statement takes the following format:

while( expression ) 
      statement       // loop body 

When entering the loop, the controlling expression is verified.

If this value is true, the loop body is then executed before the controlling expression is evaluated once more.

If the controlling expression is false, the program goes on to execute the statement following the while loop.

int count = 0; 
while( count < 10) 
   cout << ++count << endl; 

The controlling expression is normally a boolean expression.

The controlling expression might be any expression that can be converted to the bool type including any arithmetic expressions.

The value 0 converts to false and all other values convert to true.

The following code shows how to compute the average of numbers.

Demo

#include <iostream> 
using namespace std; 

int main() /*from  w  ww  .j a  v a 2s. c  o m*/
{ 
    int x, count = 0; 
    float sum = 0.0; 

    cout << "Please enter some integers:\n" 
               "(Break with any letter)" 
           << endl; 
    while( cin >> x ) 
    { 
        sum += x; 
        ++count; 
    } 
    cout << "The average of the numbers: " << sum / count << endl; 
    return 0; 
}

Result

Blocks

To repeat more than one statement in a program loop, place the statements in a block marked by parentheses { }.

A block is syntactically equivalent to a statement, so you can use a block wherever the syntax requires a statement.

Related Topic