Define looping. Discuss the types of looping structures used in C with examples.
Looping:
The loop or iteration construct, directs a
program perform a set of operation again and again until a specified condition
is achieved.
This condition causes the termination
of the loop.
C contains three statements for
looping:
Ø
While Loop: While loop construct contains the condition
first. If the condition is satisfied the control executes the statement
following the while loop exile, it ignores these statements.
Syntax: while(condition)
{ statement1
Statement2
}
Example: : #include<stdio.h>
#include<conio.h>
void main()
{
int
x;
X=1;
while(x<10)
{
printf(“x
is %d /n”, x);
x++;
}
}
Ø
Do While Loop:
Do while loop ensure that the
program execute at least once and checks whether the condition at the end of
the do-while loop is true or false.
As long as the test condition is true
the statement will be repeated. The control will come out from the loop only
when the test condition is false.
Syntax: do
{
Statement1
Statement1
}while(condition)
Example: : #include<stdio.h>
#include<conio.h>
void main()
{
int
x;
X=1;
do
{
printf(“x
is %d /n”, x);
x++;
}
while(x<10)
}
Ø
For loop construct is used to execute a set of
statements for a given number of times.
Thus, it is a shorthand method for executing statement in a loop.
Syntax: for(initial condition; test condition; increment or
decrement)
{ Statement1
Statement2
}
Example: #include<stdio.h>
#include<conio.h>
void main()
{
int
counter;
for(counter=20;
counter<=1; counter--)
{
printf(“%d”,
counter);
}
}
0 comments:
Post a Comment