Iterative Statement: do-while Loop
It is another repetitive control structure provided by C++. It is an exit control loop. It evaluates its test-expression after executing its loop body statements. A do-while loop always executes at least once.
The syntax of the do-while loop is
do
{
statement;
}
while <condition>;
where
do is a reserved word
statment can be simple or compound statment
while is a reserved word
<condition> is a Boolean expression
Its functionality is exactly the same as the while loop except that condition in the do-while is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, the following program echoes any number you enter until you enter 0.
// number echoer Output:
#include <iostream.h> Enter number (0 to end): 12345
int main () You entered: 12345
{ Enter number (0 to end): 160277
unsigned long n; You entered: 160277
do { Enter number (0 to end): 0
cout << "Enter number (0 to end): "; You entered: 0
cin >> n;
cout << "You entered: " << n << "\n";
} while (n != 0);
return 0;
}
The do-while loop is usually used when the condition that has to determine its end is determined within the loop statement, like in the previous case, where the user input within the block of intructions is what determines the end of the loop. If you never enter the 0 value in the previous example the loop will never end.