Saturday, December 11, 2010

Loops2

the while statement

The while statement has the form:
while(condition) {
   // code to execute 
};

  • condition is a boolean statement that is checked each time after the final "}" of the while statement executes. If the condition is true then the while statement executes again. If the condition is false, the whilestatement does not execute again.
As an example, let's say that we wanted to write all the even numbers between 11 and 23 to the screen. The following is a full C++ program that does that.
// include this file for cout
#include <iostream.h>

int main(){
   // this variable holds the present number
   int current_number = 12;

   // while loop that prints all even numbers between
   // 11 and 23 to the screen
   while (current_number < 23){
      cerr << current_number << endl;
      current_number += 2;
   }
   cerr << "all done" << endl;
}   
The preceding example prints the value of current_number to the screen and then adds 2 to its value. As soon as the value of the variable current_number goes above 23, the while loop exits and the next line is executed.
The output of the preceding program would be:
12
14
16
18
20
22
all done

No comments:

Post a Comment