1). For loop
For loop is used to execute a set of statements repeatedly until a particular condition is satisfied. We can say it is an open ended loop.
In for loop we have exactly two semicolons, one after initialization and second after the condition. In this loop we can have more than one initialization or increment/decrement, separated using comma operator. But it can have only one condition
The for loop is executed as follows:.
- It first evaluates the initialization code.
- Then it checks the condition expression.
- If it is true, it executes the for-loop body.
- Then it evaluate the increment/decrement condition and again follows from step 2.
- When the condition expression becomes false, it exits the loop.
Syntax:-
for(initialization; condition; increment/decrement)
{
statement-block;
}
Example:-
#include<stdio.h>
#include<conio.h>
void main( )
{
int x;
for(x = 1; x <= 10; x++)
{
printf("%d\t", x);
}
getch();
}
Output:- 1 2 3 4 5 6 7 8 9 10
2). While loop
loop can be addressed as an entry control loop. It is completed in 3 steps.
- Variable initialization.(e.g
int x = 0;) - condition(e.g
while(x <= 20)) - Variable increment or decrement (
x++orx--orx = x + 2)
Syntax:-
variable initialization;
while(condition)
{
statements;
variable increment or decrement;
}
Example:-
#include<stdio.h>
#include<conio.h>
void main( )
{
int x;
x = 1;
while(x <= 10)
{
printf("%d\t", x);
/* below statement means, do x = x+1, increment x by 1*/
x++;
}
getch();
}
Output:- 1 2 3 4 5 6 7 8 9 10
3). do-while loop
In some situations it is necessary to execute body of the loop before testing the condition. Such situations can be handled with the help of
do-while loop. do statement evaluates the body of the loop first and at the end, the condition is checked using while statement. It means that the body of the loop will be executed at least once, even though the starting condition inside while is initialized to be false.Syntax:-
do
{
.....
.....
}
while(condition)
Example:-
#include<stdio.h>
#include<conio.h>
void main()
{
int a, i;
a = 5;
i = 1;
do
{
printf("%d\t", a*i);
i++;
}
while(i <= 10);
}
Output:- 5 10 15 20 25 30 35 40 45 50
0 Comments