You may encounter situations, when a block of code needs to be executed
several number of times. In general, statements are executed sequentially:
The first statement in a function is executed first, followed by the second, and so on
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements
Types Of Loop
1. while loop
2.Do while loop
3.for loop
1.while loop :
In while loop First check the condition if condition is true then control goes inside the loop body
other wise goes outside the body. while loop will be repeats in clock wise direction.
Syntax:
Assignment;
while(condition)
{
Statements;
......
Increment/decrements (++ or --);
}
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
int i;
clrscr();
i=1;
while(i<5)
{
printf("\n%d",i);
i++;
}
getch();
}
Output:
1
2
3
4
2.Do while loop :
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.
Syntax:
do {
statement(s);
} while( condition );
Example:
#include <stdio.h>
#include <conio.h>
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
Output :
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
3.for loop :
When we need to repeat the statement block at least 1 time then we use do-while loop.
This loop is generally used for performing a same task, a fixed number of times.
Syntax:
while (condition test)
for ( init; condition; increment ) {
statement(s);
}
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<5;i++)
{
printf("\n%d",i);
}
getch();
}
Output :
Comments
Post a Comment