- c-language support two types of loops they are
- pretest loop(entry controlled loop)
if expression is true it execute body of the loop otherwise it termites body of the loop.
example: while,forwhile loop:
- while loop is a pretest loop it execute body of the loop 1 or more times until condition is true.
syntax: while(expression)
{
body;
}
statement x;
/*program to generate positive integers */
#include<stdio.h>
#include<conio.h>
main()
{
int i=1;
clrscr();
while(i<=5)
{
Printf(“\n %d”,i);
i=i+1;
}
getch();
}
Output:
1
2
3
4
5
For loop:
- for loop is pre tested or entry tested loop i.e condition is tested at the begining of the loop.
syntax: for(initialization;condition;increment/decrement);
{
body;
}
statement x;
working of for loop
- first it execute initialization then test the condition if it is true execute statements/body of for loop.
- then execute increment/decrement and test the condition again if it is true.
- when condition is false go out of loop and execute statements outside the loop.
/*program to generate even numbers*/
working of for loop
- first it execute initialization then test the condition if it is true execute statements/body of for loop.
- then execute increment/decrement and test the condition again if it is true.
- when condition is false go out of loop and execute statements outside the loop.
#include<conio.h>
main()
{
int i,n;
clrscr();
print f(“enter n value”);
scanf(“%d”,&n);
for(i=2;i<=n;i=i+2)
{
Printf(“\n %d”,i);
}
getch();
}
Output:
Enter
n value 10
2
4
6
8
10
- post test loop(exit controlled loop)
example: do...while
do...while
- do while loop is also called as exit controlled loop
- it execute the body of loop one or more times.
{
body;
}while(expression);
statement x;
#include<stdio.h>
#include<conio.h>
main()
{
int i=1;
clrscr();
do{
printf(“%d”,i);
i=i+1;
}while(i<10);
getch();
}
Output:
123456789
You can also refer
----------------------------------------------------------------------------------------------------------
No comments:
Post a Comment