Advertisement

Discussion of loop


The C language provides for three loop constructs for performing loop operations. They are
Ø The while statement
Ø The do statement
Ø The for statement

THE WHILE STATEMENT

The basic format of the while statement is
The while is an entry–controlled loop statement. The test-condition is evaluated and if
the condition is true, then the body of the loop is executed. After execution of the body, the
test-condition is once again evaluated and if it is true, the body is executed once again. This
process of repeated execution of the body continues until the test-condition finally becomes
false and the control is transferred out of the loop.
Body of the loop
test
condn?
while(test condition)
{
body of the loop
}
Sample::
sum = 0;
n = 1;
while(n <= 10)
{
sum = sum + n* n;
n = n + 1;
}
printf(“sum = %d \n”,sum);
-----------

THE DO STATEMENT
In while loop the body of the loop may not be executed at all if the condition is not
satisfied at the very first attempt. Such situations can be handled with the help of the do
statement.
Since the test-condition is evaluated at the bottom of the loop, the do…..while construct
provides an exit-controlled loop and therefore the body of the loop is always executed at least
once.
Eg:
-----------
do
{
printf(“Input a number\n”);
number = getnum();
}
while(number > 0);



THE FOR STATEMENT

Simple ‘for’ Loops
The for loop is another entry-controlled loop that provides a more consise loop control
structure. The general form of the for loop is

for(initialization ; test-condition ; increment
{
body of the loop

}
Example::
for(x = 0; x <= 9; x = x + 1)
{
printf)”%d”,x);
}
printf(“\n”);



Nesting of For Loops
C allows one for statement within another for statement.
----------
----------
for(i = 1; i < 10; ++ i)
{
---------
---------
for(j = 1; j! = 5; ++j)
{ Inner Outer
--------- loop loop
---------
}
---------
---------
}
----------
----------
Eg:
----------
----------
for(row = 1; row <= ROWMAX; ++row)
{
for(column = 1; column < = COLMAX; ++column)
{
y = row * column;
printf(“%4d”, y);
}
printf(“\n”);
}
----------
----------
JUMPS IN LOOPS
C permits a jump from one statement to another within a loop as well as the jump out
of a loop.
Jumping out of a Loop
An early exit from a loop can be accomplished by using the break statement or the
goto statement.
When the break statement is encountered inside a loop, the loop is immediately
exited and the program continues with the statement immediately following the loop. When
the loops are nested, the break would only exit from the loop containing it. That is, the break
will exit only a single loop.

Skipping a part of a Loop
Like the break statement, C supports another similar statement called the continue
statement.


continue;

The use of continue statement in loops.
 while(test-condition)
{
---------
if(--------)
continue;
----------
----------
}




No comments:

Post a Comment

Please comment bellow. Share your knowledge