The Do/While Definition
The C++ Do/Do-While loops are 1st class tools to iterate through Arrays, Process Input, output from a database query and much more.
Their definitions look like this:
do Statement; while(condition);
do{
Statement;
} while(condition);
while(Condition) Statement;
while(Condition)
{
Statement;
};
The DO loop will always execute the loop at least once. It evaluates the While Condition after each iteration to determine if another iteration is in order.
In the WHILE loop, Condition is always evaluated first before each iteration. This means you could have ZERO iterations with a statement such as:
while(77 > 100)
cout << "SEE? Math is broken << endl;
As always in C and C++, you can replace a single statement with a body, enclosed by curly brackets. The two snippets below show how a DO loop can have a single statement or a body.
x = 0;
do
cout << x++ << endl; // Outputs 0-9
while (x < 10);
x = 0;
do {
cout << x++ << endl; // Outputs 0-9
} while (x < 10);
And the same can be done with the WHILE loop.
x = 0;
while (x < 10)
cout << x++ << endl; // Outputs 0-9
x = 0;
while (x < 10)
{
cout << x++ << endl; // Outputs 0-9
}
Break out, or Continue
As with the FOR loop, the Do and Do-While loops let you use the Break keyword to break out of the loop. For example:
x = 0;
while (1) {
cout << x;
if (++x > 9)
break;
}
>> 0123456789
x = 0;
do {
cout << x;
if (x++ > 8)
break;
} while (1);
>> 0123456789
.. And the Continue keyword starts a new iteration, skipping any remaining code within the loop.
x = -1;
while (++x <= 9) {
if (x > 3 && x < 6)
continue;
cout << x;
}
>> 01236789
x = 0;
do{
if (x > 3 && x < 6)
continue;
cout << x;
} while (++x <= 9);
Nesting Your Loops
And of course, you can nest Do and Do-While loops within each other.
x = 0;
while (x < 5) {
y = 0;
while (y < 3) {
cout << x << " " << y++ << endl;
}
x++;
}
---------------------------
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
3 0
3 1
3 2
4 0
4 1
4 2
x = 0;
do {
y = 0;
do
cout << x << " " << y++ << endl;
while (y < 3);
}while(x++ < 5);
---------------------------
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
3 0
3 1
3 2
4 0
4 1
4 2
5 0
5 1
5 2
Conclusion
The Do and Do-While loops are an excellent tool for nearly any situation where a counting variable may not be enough to know when to exit a loop. For example, when gathering input :
do {
x = GetInput();
// Do some other stuff
} while (x != 27); // 27=ESC key