do..while is just loke a while loop, except
that
- it always executes the first time
- it checks the
continuation condition AFTER each loop
In do..while and while loops, don't forget to include some sort of counting command, or some other command that changes something. Otherwise, you could have an infinite loop.
Trace this loop and predict what will be printed.
int n = 7;
do
{
output(n);
n = n +
7;
if (n >
10)
{ n = n - 10;
}
} while(n != 0) ;
7 , 4 , 1 , 8 , 5 , 2 , 9 , 6 ,
3 ... stops at n == 0
because 7 + 7 = 14,
and 14>10, so n = 14 - 10 =
4
4 + 7 = 11, and 11>10, so n = 11 - 10 =
1
... etc ... until 3 + 7 = 10 and 10-10 = 0
.