do----while Loop
‘C’ program implements a
post-test loop using a structure called a do...while loop.
The do...while loop
structure, is used to execute a block of statements in a unspecified number of
times while a condition is true.
If the condition is
false on the first pass, the statements are not executed.
/* Demonstrate while and
do...while loops. */
#include<stdio.h>
int main(void)
{
//local declarations
int loopCount;
//statements
loopCount=5;
printf("while
loop:");
while(loopCount>0)
print("%3d",
loopcount--);
printf("\n\n");
loopCount=5;
printf("do...while
loop:");
do
printf("%3d",
looCount--);
while(loopCount>0);
printf("\n");
return 0;
} //end main
OUTPUT:
while loop: 5 4 3 2 1
do...while loop: 5 4 3 2
1
Loop comparison in Counter – Controlled Loop
Pre-test loop
|
Post-test loop
|
||
Initialization:
|
1
|
Initialization:
|
1
|
Number of tests:
|
n+1
|
Number of tests:
|
n
|
Action executed:
|
n
|
Action executed:
|
n
|
Updating executed:
|
n
|
Updating executed:
|
n
|
Minimum iterations:
|
0
|
Minimum iterations:
|
1
|
Comparison of while and for loop
The break statement,
when executed in a while, for, do...while or switch statement, causes immediate
exit for that loop.
The common use of the
break statement is to skip from the loop.
Eliminating the Break in Loops
Continue Statement
The continue statement,
when executed in a while, for or do...while structure, skips the remaining
statements in the body of that structure and proceeds with the next iteration
of the loops.
Unlike break, the
continue statement doesn’t terminate a loop, but transfers control to the
testing expression (in while and do...while loops) or the update expression (in
for loops).
Summary
At loop is a programming
structure that allows an action to repeat until the program meets a given
condition.
In pre-test loop each
iteration, the program tests the condition first before executing the loops
block.
In post-test loop each iteration,
the program executes the loops block first and tests against a condition.
A while loop is an event
controlled loop. It is a control flow statement that, allows the code to be
executed repeatedly based on a given condition.
A ‘for loop’ is a
pre-test loop that includes three expressions in its header:
-Loop initialization
statement
-Limit test expression
-Loop update statement
The do...while loop
structure, is used to execute a block of statements in a unspecified number of
times while a condition is true. If the condition is false on the first pass,
the statements are not executed.