Loop
Loop
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
2
UNDERSTANDING LOOP
3
LOOP IN C
PROGRAMMING
Md Shafiuzzaman
Lecturer,
Dept. of CSE, NBIU
4
FOR LOOP
A for loop provides a concise way of writing the loop structure.
Unlike a while loop, a for loop declaration consumes the
initialization, condition, and increment/decrement in one line
thereby providing a shorter, easy-to-debug structure of looping.
Syntax
for (initialization condition; testing condition;
increment/decrement)
{
// statement(s)
}
FOR LOOP
#include<stdio.h>
int main()
{
int i, sum=0;
2 + 5 + 8 + . . . . . . . . . . . + 98
for(i=2; i<=98; i=i+3)
Find the sum of the above series {
using for loop. sum=sum+i;
}
printf("%d",sum);
}
WHILE LOOP
A while loop is a control flow statement that
allows code to be executed repeatedly based
on a given Boolean condition.
The while loop can be thought of as a
repeating if statement.
Syntax
initialization;
while (boolean condition)
{
// loop statements...
}
WHILE LOOP
#include<stdio.h>
int main()
{
int i, ans=1;
3 × 8 × 13 × . . . . . . . . . . . × 98
i=3;
Find the multiplication of the while ( i<=98 )
above series using while loop. {
ans = ans * i;
i=i+5;
}
printf("%d“ ,ans);
}
DO WHILE
do while loop is similar to while loop with the only difference
that it checks for the condition after executing the statements,
and therefore is an example of Exit Control Loop.
Syntax
initialization;
do
{
statements..
}
while (condition);
DO….WHILE LOOP
#include<stdio.h>
int main()
{
int i, sum=0;
5 + 30 + 180 + . . . . . . . . . . . + n
i=5;
Find the sum of the above series do{
using do….while loop. sum = sum + i;
i=i*6;
} while ( i <= n );
printf("%d“ ,sum);
}
DIFFERENCE BETWEEN FOR LOOP
AND WHILE LOOP
for Loop while Loop
Initialization may be either in the loop statement or outside
Initialization is always outside the loop.
the loop.
The increment can be done before or after the execution of the
Once the statement(s) is executed then increment is done.
statement(s).
It is normally used when the number of iterations is known. It is normally used when the number of iterations is unknown.
Syntax: for ( init ; condition ; iteration ) { statement(s); } Syntax: while ( condition ) { statement(s); }