Greetings,
The while loop operates as follows:
while (expression)
statement
The condition in parenthesis is tested. If it is true, the body of the loop is executed. Then the condition is re-tested, and if true, the body is executed again. When the test becomes false the loop ends, and the execution continues at the statment that follows the loop.
By contrast the
do-while loop tests at the bottom after making each pass through the loop body. The body is always executed at least once. Here are the following syntax:
do {
statement
while (expression); The statment is executed, then expression is evaluated. If it is true, statment is evaluaged again, and so on. When the expression becomes false, the loop terminates.
Using a while loop in our case would not be difficult. It seems like you are wanting to do a
while loop inside a
do-while loop. The infinite loop for while would contain 1. 1 usually means true, and 0 determines false. Calling something like:
Will never end, unless broken by other means, such as break and return.
In this case, we could do somewhat the following:
int i=0;
// Infinite loop
while (1) {
// Loop three times [i < 3]
do {
// Do stuff
i++; // Be sure to increment, or loop will never terminate.
} while (i < 3);
break; // Break infinite loop
} The reason this works is because we infinitely call our
do-while loop, though it only goes by once. Our while(1) calls on break once our
do-while loop is finished.
i increments 3 times before the
do-while is over, hence (i < 3), and once that is over it continues to resume after our loop statement; which is break.
Hope this helps,
-
Stack
Overflow