The do…while statement uses the following syntax:
do Statement while (Condition);
The do…while condition executes a Statement first. After the first execution of the Statement, it examines the Condition. If the Condition is true, then it executes the Statement again. It will keep executing the Statement AS LONG AS the Condition is true. Once the Condition becomes false, the looping (the execution of the Statement) would stop.
If the Statement is a short one, such as made of one line, simply write it after the do keyword. Like the if and the while statements, the Condition being checked must be included between parentheses. The whole do…while statement must end with a semicolon.
Another version of the counting program seen previously would be:
do Statement while (Condition);
The do…while condition executes a Statement first. After the first execution of the Statement, it examines the Condition. If the Condition is true, then it executes the Statement again. It will keep executing the Statement AS LONG AS the Condition is true. Once the Condition becomes false, the looping (the execution of the Statement) would stop.
If the Statement is a short one, such as made of one line, simply write it after the do keyword. Like the if and the while statements, the Condition being checked must be included between parentheses. The whole do…while statement must end with a semicolon.
Another version of the counting program seen previously would be:
#include <iostream>
void main()
{
int Number = 0;
do
cout << "Number " << Number++ << endl;
while( Number <= 12 );
getch();
}
If the Statement is long and should span more than one line, start it with an opening curly braket and end it with a closing curly bracket.
The do…while statement can be used to insist on getting a specific value from the user. For example, since our ergonomic program would like the user to sit down for the subsequent exercise, you can modify your program to continue only once she is sitting down. Here is an example on how you would accomplish that:
#include <iostream>
void main()
{
char SittingDown;
cout << "For the next exercise, you need to be sitting down\n";
do {
cout << "Are you sitting down now(y/n)? ";
cin >> SittingDown;
}
while( !(SittingDown == 'y') );
cout << "\nWonderful!!!";
getch();
}
|
0 comments:
Post a Comment