Loop statement In C Language
Loop
are used to repeat a block of statement for a certain time.
There are three type of loop they are:
1.while
loop
2.do-while
loop
3.for
loop
1.while loop
This
loop execute a statement or a block of statement until the specified Boolean expression
evaluates to false.
Syntax:
While(expression)
{
//statement
}
Fig: While loop |
Program
#include<stdio.h>
#include<conio.h>
void
main()
{
int
i=1;
while(i<=5)
{
printf(“%d\n”,i);
i++;
}
getch();
}
Output:
1
2
3
4
5
2.do-while loop
This
loop execute a statement or a block of statement until the specified Boolean expression
evaluates to false.
Syntax:
do
{
//statement
}
while(expression);
Fig: do-while loop |
Program
#include<stdio.h>
#include<conio.h>
void
main()
{
char
choice=’Y’;
do
{
int
number=5;
printf(“\n
print number :%d”,number);
printf(“\n
Do you want to Continue (y/n) :”);
scanf(“%c”,
&choice);
}
while(choice==’y’);
getch();
}
Output:
Print
number :5
Do
you want to continue (y/n) : y
3. for loop
This
loop has three sections-index declaration, condition(Boolean expression) and
updating section, in each for loop iteration the index is update(incremented/decremented) by updating section and checked with condition.
If the condition is matched, it continue execution until the specified Boolean expression
evaluates to false.
Syntax:
for(initialization
statement, condition, increment/decrement)
{
//statement;
}
Fig: for loop |
Program
#include<stdio.h>
#include<conio.h>
void
main()
{
int
a,f,i;
printf(“Enter
a number : “);
scanf(“%d”,&a);
f=1;
for(i=1;i<=a;i++)
f=f*i;
printf(“factorial : %d”, f);
getch();
}
Output:
Enter
a number :5
Factorial:
120
No comments:
Post a Comment