The Loop Constructs:-
The loop directs a program to perform
a set of operation again and again until a specified condition is true.
Looping statement is used when we want
to execute statement or statements until a condition is true. ‘C’ contains
following type of looping statement-
- The for loop
- The while loop
- The do-while loop
For Loop:-
For loop is used to execute a set of
statement(s) for a given number of times, means if we want to execute
statement(s) till a certain number of time, for loop is used.
Syntax:-
for (start value; end value;
increment/decrement)
{
Statement1;
Statement2;
}
While Loop:-
While loop statement contains the
condition first. If the condition is satisfied, the control executes the
statements of the while loop else, it ignores these statements.
Syntax:-
while (condition)
{
Statement1;
Statement2;
}
Example:-
#include
<stdio.h>
int
main()
{
int
i;
i=1;
while(i<6)
{
printf(“Ouch!
Please stop!\n”);
i++;
}
return(0);
}
Here’s
what the output looks like:
Ouch! Please stop!
Ouch!
Please stop!
Ouch!
Please stop!
Ouch!
Please stop!
Ouch!
Please stop!
Do-While Loop:-
Do-while loop statement is another
method used in C. Do-while loop ensures that the program is executed 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 statements will be repeated.
Syntax:-
do
{
Statement1;
Statement2;
}
while (condition);
Example:-
#include
<stdio.h>
void
main()
{
int
start;
printf(“Please
enter the number to start\n”);
printf(“the
countdown (1 to 100):”);
scanf(“%d”,&start);
/*
The countdown loop */
do
{
printf(“T-minus
%d\n”,start);
start--;
}
while(start>0);
printf(“Zero!\nBlast
off!\n”);
return(0);
}
Run the program.
Please
enter the number to start
the
countdown (1 to 100):
Be
a traditionalist and type 10. Press Enter:
T-minus
10
T-minus
9
et
cetera . . .
T-minus
1
Zero!
Blast
off!
No comments:
Post a Comment