The Loop Control structure

·

These are three methods by way of which we can repeat a part of a program.
They are:
(a) Using a for statement
(b) Using a while statement
(c) Using a do-while statement

The while Loop:-
The general from of while is as shown below:
initialise loop counter;
while (test loop counter using a condition)
{
do this;
and this;
increment loop counter;
}
The parentheses after the while contains a condition so long as this condition remains true all
statements within the body of the while loop keep getting executed repeatedly
for e.g.
/* calculation of simple interest for 3 sets of p, n and r */
main( )
{ int p,n, count; float r, si;
count = 1;
while(count < = 3 )
{
printf(“\n Enter values of p, n and r”);
scanf(“%d %d %f”, & p, & n, & r);
si = p*n*r/100;
printf(“simple interest = Rs. %f”, si);
count = count +1;
}


The do-while Loop
The do-while loop takes the following form
do
{
this;
and this; and this; and this;
} while (this condition is true);


There is a minor difference between the working of while and do-while loops. The difference is the place where the condition is tested. The while tests the condition before executing any of the statements within the while loop. As against this the do-while tests the condition after having executed the statements within the loop.
e.g:-
main( )
{
while(5<1)
printf(“Hello \n”);
}
In the above e.q. the printf will not get executed at all since the condition fails at the first time itself. Now let’s now write the same program using a do-while loop.
main( )
{
do
{
printf (“Hello \n”);
} while (5<1);
}
In the above program the printf( ) would be executed once, since first the body of the loop is executed and then the condition is tested.

The for Loop
The general form of for statement is as under:
for( initialise counter; test counter; increment counter)
{
do this; and this; and this;
}
Now let us write the simple interest problem using the for loop
/* calculation of simple interest for 3 sets of p,n and main( )
{
int p,n, count;
float r, si;
for(count = 1; count <=3; count = count +1)
{
printf(“Enter values of p,n and r”);
scanf(“%d %d %f”, & p, & n, & r);
si = p * n * r / 100;
printf(“Simple interest = Rs %f \n”, si);
}
}

About Me

Blog Archive