Code About Us Tutorial


  Statements & Expression
    The while Statement
    The do ... while Statement
    The for Statement
    The break Statement
    The continue Statement
    The goto Statement
    The switch Statement
    Keywords
    Scope Resolution (::)
    Arithmatic Operators


   
 

Home > Statements & Expression > The while Statement

December 2, 2009 7:40 am

   

The while Statement

Now we can move onto more advanced statements such as the while statement, the do...while statement, and the for statement. The while statement has the syntax:

while (condition) statement;

First the condition is evaluated. If it is nonzero(true), the statement is executed and the condition is evaluated again. These two steps are repeated until the condition evaluates to zero (false). Here is an example of how the while statement works:

 
 
#include <iostream.h>

int main() { int n = 0; cout <<"Enter an integer: "; cin >> n; while (n > 0) { cout << n << " cubed is: " << n * n * n << endl; cin >> n; } return 0; }

The above program first asks the user to enter a number, then it checks the condition (n > 0). If you entered the number 3, the condition would evaluate as true, and execute the code in the block. The program will continue to ask the user for another number to cube, if you want it to stop then you would have to type the number 0. If you did type in a 0, the condition would evaluate false and the loop would end. You could also write this same code using a do while statement. Please Rate this Code:


    Comments for: The while Statement
Annonymouse User says:
Both the syntax and the explanation for the while statement are sound and well thought out. It might be a good idea to tell the user how to quit. i.e. cout << \"Enter an integer(0 to quit) \";

Annonymouse User says:
Both the syntax and the explanation for the while statement are sound and well thought out. It might be a good idea to tell the user how to quit. i.e. cout << \"Enter an integer(0 to quit) \"; says:
it is easy.jhjidhnkjhj




Add Comment:
Name:
Email:


 «10» THINKQUEST TEAM C0111571 © 2001. All Rights Reserved.