In: Computer Science
Foundation of Computer Science
Discuss the repetition constructs. Give an illustrative example for each one of them.
Repetition constructs , or loops, are used when a program needs
to repeatedly
process one or more instructions until some condition is met, at
which time the
loop ends. The process of performing the same task over and
over
again is called iteration.
A loop executes the same part of program code over and over again,
as long as
a loop condition with each repetition. This section of code
can be a single statement or a block of statements (a compound
statement).
There are three types
of repetition constructs:
1. for loop
2. while loop
3. do ... while loop
Syntax of for loop:
for(expression 1; condition; expression 2){
--body of the loop--
}
Steps of execution:
Step 1: The control first goes to expression 1.
Step 2: Then it goes to condition. If it is true,
then it enters body of the loop and executes it. After that, it
goes to expression 2.
Then again to Step 2. If the condition is false, then loop breaks
and control comes out of the loop
Example of for
loop:
To print Natural Numbers from 1 to 10:
for(int i=1;i<=10;i++){
printf("%d ",i);
}
// Output:
1 2 3 4 5 6 7 8 9 10
Syntax of while loop:
while(condition){
--body of loop--
}
Steps of execution:
Step 1: The control first goes to condition.If it is true, then it
goes to body. If it is false, then it comes out of loop.
Step 2: Control goes to the body of the loop, executes it and goes
back to Step 1.
Example of while
loop:
To print Natural Numbers from 1 to 10:
int i = 1;
while(i<=10){
printf("%d ",i);
i++;
}
// Output:
1 2 3 4 5 6 7 8 9 10
Syntax of do while loop:
do{
--body of loop--
}
while(condition);
Steps of
execution:
Step 1: The statement executes first, and then expression is
evaluated
Step 2: If expression evaluates to true, statement executes
again
Step 3: As long as expression in a do...while statement is true,
statement executes
Step 4: Like other loops, to avoid an infinite loop, loop body must
contain a statement that makes expression false
Step 5: Statement can be simple or compound (multiple statements);
if compound, they must be in braces
Example of do ... while
loop:
To print Natural Numbers from 1 to 10:
int i = 1;
do{
printf("%d ",i);
i++;
}
while(i<=10);
// Output:
1 2 3 4 5 6 7 8 9 10