Using Do-while statements to form loops
The Do-while statement is characterized by executing the loop body first, and then judging whether the cyclic condition is tenable. Its general form is:
Do
statement while
(expression);
It is done in this way: executes the specified statement (that is, the loop body) first, and then the expression, which, when the value of the expression is not 0 ("true"), returns the recurring loop-body statement, repeated until the value of the expression equals 0, and the loop ends. You can use the following figure to represent its process.
"Example" uses the Do-while statement to seek 1+2+3+...+100.
#include <iostream>
using namespace std;
int main ()
{
int i=1,sum=0;
Do
{
sum=sum+i;
i++;
}
while (i<=100);
cout<< "sum=" <<sum<<endl;
return 0;
}
You can see that the same problem can be handled with a while statement, or you can use a do-while statement. The Do While statement structure can be converted to a while structure.
A comparison of several cycles of C + + :
1 The 3 loops, for and while and do, can be used to handle the same problem, and in general they can be substituted for each other.
2 while and do-while loops, which specify the loop condition after the while, should include statements (such as i++, or i=i+1, etc.) that tend to end the loop in the loop body.
The For loop can include an operation that tends to end the loop in Expression 3, and even put all the operations in the loop body into expression 3. The For statement is therefore more powerful and can be implemented with a for loop where the while loop can be done.
3 when using while and do-while loops, the operation of the loop variable initialization should be done before the while and Do-while statements. The For statement can implement the initialization of the loop variable in expression 1.
nested nesting of loops
A loop body also contains another complete loop structure, called a loop nesting. Loops can also be nested within a loop, which is a multilayer loop.
3 Loops (while loops, do while loops and for loops) can be nested with each other. For example, the following are all legal forms:
while ()
{while
()
{...}}
}
Do
{do {
...} while ();
} while ();
for (;;)
{for
(;;)
{...}}
while ()
{
do
{...} while ();
}
for (;;)
{while
()
{...}}
}
Do
{for
(;;)
{...}}
while ();