Tuesday 12 February 2013

The do - while Loop in C Programming Language


The do - while loop, like the while loop, is used in situations where the number of iterations to be performed is not known, and is dependant on a condition which changes within the loop-body. Also, iterations are to be performed until the specified loop condition becomes false

It differs from the while loop in that the body of the loop is executed at least once, and the condition is evaluated for subsequent executions.

The following program uses the do - while loop for the menu program written earlier using the while loop.

#include <stdio.h>
main()
{
char chc,ok;
do
{
ok='';
switch(chc)
{
case '1' : puts("1");
break;
case '2' : puts("2");
break;
default : puts("Invalid Choice");
ok='n';
}
}
while(ok=='n');
}

The initialisation, ok='n', is required, to enter a while loop, whereas this step is not required in the function that uses the do - while loop. This is a better loop to use when the body has to be executed at least once before the loop condition has to be evaluated.

0 comments:

Post a Comment

Powered by Blogger.