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 multiple times.
Types of Loop
There are 3 types of Loop in C language:
1. while loop
2. for loop
3. do while loop
1. while loop
while loop can be addressed as an entry control loop.
Syntax :
variable initialization;
while(condition)
{
statements;
variable increment or decrement;
}
Example:
#include<stdio.h>
void main( )
{
int x;
x = 1;
while(x <= 10)
{
printf("%d\t", x);
x++; /* x = x+1, increment x by 1*/
}
}
2. 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.
Syntax:
for(initialization; condition; increment/decrement)
{
statement-block;
}
Example:
#include<stdio.h>
void main( )
{
int x;
for(x = 1; x <= 10; x++)
{
printf("%d\t", x);
}
}
3. Nested for loop
Syntax:
for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
statement ;
}
}
Example:
#include<stdio.h>
void main( )
{
int i, j;
for(i = 1; i < 5; i++) /* first for loop */
{
printf("\n");
for(j = i; j > 0; j--) /* second for loop inside the first */
{
printf("%d", j);
}
}
}
4. do-while loop
In some situations it is necessary to execute body of the loop before testing the condition.
Syntax:
do
{
.....
.....
}
while(condition);
Example:
#include<stdio.h>
void main()
{
int a, b;
a = 5;
b = 1;
do
{
printf("%d\t", a*b);
b++;
}
while(b<= 10);
}
Loop control statements : Loop control statements are used to change the normal sequence of execution of the loop
|
Statement |
Syntax |
Description |
|
break statement |
break; |
Is used to terminate loop or switch statements. |
|
continue statement |
continue; |
Is used to suspend the execution of current loop iteration and
transfer control to the loop for the next iteration. |
|
goto statement |
goto labelname; labelname : statement; |
It transfers the current program execution sequence to some
other part of the program. |
No comments:
Post a Comment