Looping Statement in C
Loop is used to execute the block of
code several times according to the given condition in loop. It means it
executes the same code multiple times.
There are 3 types of loop
–
01.
while loop
02.
do – while loop
03.
for loop
1. while Loop –
While loop is also
known as a pre-tested loop. In general, a while loop allows a part of the code
to be executed multiple times depending upon a given condition. The while loop
is mostly used in the case where the number of iterations is not known in
advance.
Syntax of while loop :
while(condition)
{
statements – 1
statements – 2
.
.
statements – n
//increment / decrement operator if required
(optional)
}
Flowchart of while loop :
e.g.
//Program for printing 1 to 10 number
//by using while loop
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
while(i<=10)
{
printf("%d
",i);
i++;
}
getch();
}
2. do – while loop
It also executes the code until
condition is false. In this at least once, code is executed whether condition
is true or false but while loop is executed only when the condition is true.
Syntax :
do
{
statements – 1
statements – 2
.
.
statements – n
}
while(condition);
Flowchart of do-while loop :
e.g.
//Program for printing 1 to 10 number
//by using do-while loop
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
do
{
printf("%d
",i);
i++;
}
while(i<=10);
getch();
}
3. for Loop
It also executes the code until
condition is false. In this three parameters are given to it these are Initialization,
Condition & Increment/Decrement operators
Syntax
for(initialization; condition; increment/decrement)
{
statements – 1
statements – 2
.
.
statements – n
}
Flowchart of for loop :
e.g.
//Program for printing 1 to 10 number
//by using for loop
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=1; i<=10; i++)
{
printf("%d
",i);
}
getch();
}
Youtube video for program
No comments:
Post a Comment