Login    New User    Forgot Password    Help      

Do while statements

GO TO INDEX

Do while statements

One interesting thing about the while loop is that if the loop condition is false, the while loop may not execute at all. It is sometimes the case that we want a loop to execute at least once, such as when displaying a menu. To facilitate this, C++ offers the do while loop:

 
do
    statement;
while (condition);

The statement in a do while loop always executes at least once. After the statement has been executed, the do while loop checks the condition. If the condition is true, the CPU jumps back to the top of the do while loop and executes it again.

Here is an example of using a do while loop to display a menu to the user and wait for the user to make a valid choice:

Use do while loop to read a number

                               

#include < iostream·h>
int main() { int num; do { cout << "Enter a number (100 to stop): "; cin >> num; } while(num != 100); return 0; }

OUTPUT


Enter a number (100 to stop): 1
Enter a number (100 to stop): 2
Enter a number (100 to stop): 3
Enter a number (100 to stop): 100

In the above exmple Counter is initialized to 0 < 10 evaluates to true, so the statement block executes. The first statement is executed and prints Looping!, and the second increments counter to 1. Control then returns back to the top of the while statement. 1 < 5 evaluates to true, so the code block is executed again. The code block will repeatedly execute until counter==5, at which point 5 < 5 will evaluate to false, and the loop will exit.

GO TO INDEX