Lesson 5: Repetition / Iteration Structure
Lesson 5: Repetition / Iteration Structure
Lesson 5: Repetition / Iteration Structure
REPETITION / ITERATION
STRUCTURE
Introduction
Looping
Is a process that execute the same group of
statements for a number of times.
Loop Body
Is a group of statements that executed repeatedly.
3 looping constructs
while loop
do_while loop
for loop
(1) while loop
Best - where dont know ahead of
number of times the loop
General format:
while (expression) while (expression) {
statement; statement1;
statement2;
statement3;
}
Example:
What is wrong if the following code ?
int x = 10;
while( x < 20 )
printf(%d,x);
(1) while loop
- Sentinel Controlled Loop
Indefinite repetition
Not known in advance how many times the loop will
be executed.
Sentinel value indicates end of data
Is entered after all regular data items have been
supplied to the program.
Sentinel values are used to control repetition when:
1) The precise number of repetitions is NOT known
in advance.
2) The loop includes statements that obtain data
each time the loop is performed.
(1) while loop
- Sentinel Controlled Loop
Example
(2) do-while loop
Tests the loop continuation condition after the loop
statement is performed
The loop body will be executed at least once.
General format:
do {
do statement1;
statement1; statement2;
while (condition); statement3;
statement2; }while (condition);
statement2;
Example:
(2) do-while loop
- Sentinel controlled loop
Example:
The program is asked to enter a value that is less than 5.
If not, it warns the program user and repeats the loop so that a value within the requested range
can be entered.
Try this..
Write a program that will prompt the user
for 5 marks. Calculate the average and
display the average based on the criteria
below:-
A above 70
B 69 60
C 59 50
D 49 40
F below 40
(3) for loop
To allow you to do something an exact
number of times.
Be able to solve a problem any number of
times with different values each time.
The C for loop contains 4 parts:
1. The value at which the loop starts
2. The condition under the loop is continue.
3. The changes that are to take place for each loop.
4. The loop instructions.
General Format
for (initial-expression; conditional-expression; loop-expression)
{
loop body
}
(3) for loop
Example: