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
whilestatement executes. If the condition is true then thewhilestatement executes again. If the condition is false, thewhilestatement does not execute again.
// 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