do { body } while( condition ) ;
do-while
loop would look like:
i = 0 ; do { printf( "%d\n", i ) ; i++ ; } while( i < 10 ) ;
Now, this does the same thing as the example in the
previous part, and it doesn't
really matter which one we use since 10 is a constant
and won't change.
On the other hand, what if instead of 10 we had j
(another
variable).
Now the two versions will operate a little differently.
In particular, what happens if j
is 0, namely we are
asking it to count up from 0 to -1.
It shouldn't print anything in that case and doesn't in
the pre-test loop.
But since the body of the post-test loop is always executed at least
once, this version will print 0.
It turns out that most of the loops we create are like this.
They might not ever be executed depending on the inputs.
So we usually find the while
statement used more
often than the do-while
statement.
There is on common looping need that the do-while
is best for.
Suppose that the user is to input a number and that it must be between
0 and 100 inclusive.
We can do this with something like:
do { printf( "Enter a number: " ) ; scanf( "%d", &x ) ; } while( x < 0 || x > 100 ) ;
y
equal after this code fragment is executed?
y = 1 ; x = 5 ; do { y = x * y ; } while( y < 2 * x ) ;