Login    New User    Forgot Password    Help      

While Statements

GO TO INDEX

While Statements

The while statement is the simplest of the three loops that C++ provides. It’s definition is very similar to that of an if statement:

 
while (expression)
    statement;

A while statement is declared using the while keyword. When a while statement is executed, the expression is evaluated. If the expression evaluates to true (non-zero), the statement executes.

However, unlike an if statement, once the statement has finished executing, control returns to the top of the while statement and the process is repeated.

Let’s take a look at a simple while loop. The following program prints all the numbers from 0 and 9:

Looping With While

                               

#include < iostream·h>
int main() { int counter = 0; while(counter < 5) { counter++; std::cout << "Looping! "; } std::cout << "\nCounter: " << counter << ".\n"; return 0; }

OUTPUT

                                
Looping!  Looping!  Looping!  Looping!  Looping!
Counter: 5.

GO TO INDEX