2. Loops statement are used to repeat the execution of
Statement or blocks.
Types of loops
1. While loop
2. Do-While loop
3. For loop
Introduction
3. Basic execution of loops
A loop statement allows us to
execute a statement or group of
statements multiple times
Onces the condition becomes
false the loop terminates.
4. Syntax:
while(condition)
{
//Statements
}
While loop
Here, statement(s) may be a single statement or a
block of statements.
1. First Condition is evaluated.
2. If the condition is true then statement part is
executed then again it checks the condition.
3. If the condition is false then out of the while loop.
5. Print 1 to 5.
#include <stdio.h>
void main ()
{
int a = 1;
while( a < 6 )
{
printf("%dn", a);
a++;
}
}
While loop program
a<6 output a++
1<6 1 2
2<6 2 3
3<6 3 4
4<6 4 5
5<6 5 6
6<6==false - -
6. Syntax:
do
{
//Statements
}
while(condition);
Do-while
A do...while loop is similar to a while loop,
except the fact that it is guaranteed to execute at
least one time.
1. First statement part is executed and then the
condition part is evaluated.
2. If the condition is true then again statement
part executed and then again to the condition
part.
3. If the condition is false then out of do-while
loop.
7. Print 0 to 6
#include <stdio.h>
void main ()
{
int a = 0;
do {
printf("%dn", a);
a + +;
}
while( a < 6 );
}
Do-while program
output a++ A<6
0 1 1<6
1 2 2<6
2 3 3<6
3 4 4<6
4 5 5<6
5 6 6<6==false
8. Syntax: for ( initialization; condition; increment /decrement)
{
//statement(s);
}
1. First go for initialization.
2. Second Condition
- If the condition is true then statement part is executed and then iteration
portion.
- If the condition is false then out of the for-loop.
3 Third Iteration
-After iteration portion control goes back to condition.
For loop