2. Why looping
When similar task is performed repeatedly
then we suppose to use looping statement.
Ex: 1+2+3+…………………+100
We can directly add two or three numbers
but 100 or more !!!!!!!!
In this case we can use one addition
operator and then repeat the process.
3. For statement
The for statement is the most commonly used
looping statement in C.
The general form of for statement:
for( initialization; condition; increment/decrement)
statement (s);
Initialization of control variables is done first, using
assignment statements such as i=1.
The value of the control variable is tested using the
condition. If the condition is true then the statement(s)
will be executed; otherwise the loop is terminated.
The value of control variable is incremented or
decremented in the last section.
4. Continue…
Ex: for(x=0;x<=9;x=x+1)
printf(“%d”,x);
This for loop is executed 10 times and prints
the digits 0 to 9 in one line.
The for statement allows for negative
increments.
for(x=9; x>=0; x=x-1)
printf(“%d”,x);
This loop is also executed 10 times but
output would be from 9 to 0.
5. Continue…
More than one variable can be initialized at
a time in the for statement.
for (p=1,n=0;n<17;n++)
printf(“%d”,n);
The increment section may have more than
one part.
for(n=1,m=50; n<=m;n++,m--)
printf(“%d”,m+n);
6. Continue…
The condition may have any compound
relation and the testing need not be limited
only to the loop control variable.
for(i=1; i<20 && sum<100; ++i)
{
sum = sum + i;
printf(“%dn”, sum);
}
7. Continue…
One or more sections of for loop can be omitted.
m = 5;
for (; m!=100;)
{
printf(“%d ”,m);
m = m + 5;
}
In for loop there can have no statements.
for(j=1000; j>0;j--)
;
The above statement can be written as
for(j=1000;j>0;j--);
8. while statement
The basic format of the while statement is
while(test-condition)
{
body of the loop
}
The test-condition is evaluated first and if
the condition is true, then the body of the
loop is executed. This process of repeated
execution of the body continues until the
test-condition finally becomes false.
10. Do…while statement
The general format:
do
{
body of the loop
}while(test-condition);
The program proceeds to evaluate the body of the
loop first. At the end of the loop, the test-condition
in the while statement is evaluated. If the condition
is true, the program continues to evaluate the body
of the loop once again. This process continues as
long as the condition is true.