Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 54

Chapter 7 Looping

1
Chapter Outline
7.1 Concept of Loop
7.2 Pre-test Loop vs Post-test Loop
7.3 Loop Initialization and Update
7.4 Event-controlled Loop vs Counter-controlled Loop
7.5 Looping Control Structure in C
7.5.1 while Loop
7.5.2 for Loop
7.5.3 do-while Loop
7.6 Nested Loop
7.7 Jump Statements
7.7.1 break Statement
7.7.2 continue Statement

2
7.1 Concept of Looping
A loop is used to repeat a
block of instructions
until a condition is met.

Advantage: able to write


one set of instructions
that operates on multiple
separate sets of data.

3
7.2 Pre-Test vs Post-test Loop
Pre-Test Loop
The condition is checked
at the beginning of each false
iteration Condition

true

Actions

4
Pre-Test Loop
In each iteration (loop),
the condition is tested
false
first. Condition
If it is TRUE, the loop
continues. Otherwise,
true
the loop terminate.
This structure is possible Actions
not executing any
actions at all.

5
Pre-Test Loop
Example:
Set ball counter to 0
While box is not empty
Take a ball from box
Increase ball counter by 1
End While
Print ball counter

6
Post-test Loop
The condition is
checked at the end of
each iteration Actions

true
Condition

false

7
Post-test Loop
In each iteration, the
loop actions are
executed. Then the Actions
condition is tested.
If it is TRUE, a new
iteration stars. true
Otherwise, the loop Condition
terminates
This structure performs
the actions at least once. false

8
Post-test Loop
Example:
Set ball counter to 0
Do
Take a ball from box
Increase ball counter by 1
While box is not empty
Print ball counter

9
Exercise
1. Based on the general algorithms below, what will
happen to each type of loops if the box is initially
empty?

Pre-test: Post-test:
Set ball counter to 0 Set ball counter to 0

While box is not empty Do


Take a ball from box Take a ball from box
Increase ball counter by 1 Increase ball counter by 1
End While While box is not empty

Print ball counter Print ball counter


10
7.3 Loop Initialization and Update
Other than condition, commonly there are 2 more
processes (initialization and updating) associate
with loops.

11
Initialization
Set student counter = 1

Condition
While student counter <= 3
Print “Congratulation”
Add 1 to student count
Action End While

Updating Print “You are late”

This loop will repeat for 3 times

12
 
7.4 Event-Controlled Loop vs Counter-
Controlled Loop
Counter-Controlled Loop

Used when we know the number of times action(s) are


being repeated.

In this case, we will use a variable as a counter to repeat


the action(s).

13
Steps:
1. Declare a loop counter / control variable.
2. Assign initial value of control variable (the
initialization).
3. Increment / decrement by which the control variable
is modified each time through the loop (the
updating).
4. Specify test for the final value of the control variable
(the condition).

14
Initialize the
control variable
(student
Set student counter = 1 counter).
While student counter <= 3
Condition tests
Print “Congratulation” the value of the
Add 1 to student count control variable.
End While
Print “You are late”
Update the
control variable.

15
 
7.4 Event-Controlled Loop vs Counter-
Controlled Loop
 Event-Controlled Loop
 The loop will be terminated when an event changes the
loop control expression (condition) from TRUE to
FALSE.

16
Set total to 0
This loop keeps
Do repeating as long
Read number as the user
response with
Add number to total “Yes”.
Print “Anymore (Yes/No)?” Event: The user
Read response response.

While response = “Yes”


Print total

17
Notes:
 It is important to write your initialization, condition
and updating statements correctly. If not, the loop will
either never repeat or never stop (i.e. an endless loop).

Set student counter = 14


While student counter <= 3
Print “Congratulation”
Add 1 to student count
End While
Print “You are late”
18
Exercise
Identify each of the following situations whether it is
an event-controlled or a counter-controlled loop:
a. You are the seeker in a hide-and-seek game. You are
asked to count from 10 to 1 while your friends hide.

b. You are playing chess with your father. The game can
be won by the resignation of one player, which may
occur when too much material is lost, or if checkmate
appears unavoidable.

19
7.5 Looping Control Structure in C
3 types:
while loops
for loops
do-while loops

20
7.5.1 while loops Condition
false

It is a pre-test loop.


true
Syntax:
Actions

while (condition)
{ The braces { and }
action can be ignored if
there is only 1
statement in the
} body of a while loop.

21
Example 7.1: Memory: Output:
a=1; a 1
while (a < 5) 1 2
3
{ 4
printf("%d\n", a); end

a=a+1;
a ++;
}
printf(“end\n”);

22
Example 7.2
Write a loop to print out
the even numbers from
500 to 2 inclusive.

C Statement
Algorithm
int i=500;
set counter to 500
While counter >= 2 while(i>=2)
print counter value {
subtract 2 from counter printf(“%d ”, i);
End While
i-=2;
}
23
Exercise (a):
Write a while loop to print a row of 20 asterisks (‘*’).

Answer:

24
Exercise (b):
Write a while loop to print out odd numbers from 1 to
1001 inclusive.
Answer:

25
Exercise (c):
Modify the previous program so that it asks user how
many asterisks (‘*’) to be printed.
Answer:

26
int counter, score, total, average;
Example 7.3 total = 0;
A class of 10 students counter = 1; // Initialization
took a test. Write a while (counter <= 10) // Condition
program that reads {
the test score of every printf("Enter test score : ");
student and scanf("%d", &score);
determine the class total = total + score;
average on the test. counter++; // Updating
Given that the score is }
an integer in the range average = total / 10;
0 to 100. printf("Average is %d\n", average);

27
Previous Lecture:
 while loop:  while loop-Accumulate:
int a = 1; //initialization int a = 1, sum=0;
while (a<=5) //condition while (a<=5)
{ {
printf(“%d\n”, a); sum=sum+ a;
++a; //updating ++a;
} }

28
Looping with a variable sentinel value
 Sentinel value: a special value that causes a loop
to stop.
Used when there is no fixed number of
repetitions for the loop to execute.
For example, -1 is used as the sentinel value to stop
getting score from user.
The sentinel value chosen must not be confused
with an acceptable input value. For the above case,
-1 is chosen since there will not be any negative
scores for the test

29
printf("Enter test score (or -1 to stop) : "); Example
scanf("%d", &score); // Initialization
while (score != -1) { // If not sentinel, Condition
// Accumulate test scores
total = total + score; 
counter++; // One more test score read
  // Read next input
printf("Enter test score (or -1 to stop) : ");
scanf("%d", &score); // Updating
}
average = total / counter;  // Calculate average
// Print results
printf(“%d test scores read\n”, counter);
printf(“Total is %d\n”, total);
printf(“Average is %.2f\n”, average);
30
Example (improvement):
⚫ The previous example above may not work fine if
there is no test score entered. Modify the program so
that the average and output will be displayed only
when there is at least one test score entered.
 
If there is no test score, at which ZERO is entered.
Display the message “No test score entered”. You
can achieve this by using an if-else statement at the
end of program.

31
printf("Enter test score (or -1 to stop) : ");
scanf("%d", &score);
If (score != 0) {
while (score != -1) {
total = total + score; 
counter++;
printf("Enter test score (or -1 to stop) : ");
scanf("%d", &score);
}
average = total / counter; 
printf(“%d test scores read\n”, counter);
printf(“Total is %d\n”, total);
printf(“Average is %.2f\n”, average);
}
else
printf(“No test score entered!”);
32
7.5.2 for Loop
for loop is a pre-test loop.
A for loop is used when a loop is to be executed a
known number of times. We can do the same thing
with a while loop, but the for loop is easier to read
and more natural for counter-controlled loops.

33
for Loop
A for loop contains 3 major components:
expr1: Initialization of control variable.
expr2: Loop continuation condition.
expr3: Updating (increment / decrement) of control
variable.

for ( expr1; expr2; expr3 )


{
action
}

34
Syntax: (for loops)
expr1
(Initialization)

False
Initialization Condition Updating expr2
(Condition)

True
for ( expr1; expr2; expr3 ) Action
{
action expr3
} (updating)

35
for loop is equivalent a while loop
expr1;
while (expr2)
{
action;
expr3;
}

for ( expr1; expr2; expr3 )


{
action;
}
36
Example:
While loop: for loop:
a = 1; 1 2 4
while (a<=5) for (a=1; a<=5; a++)
{ {
printf(“%d ”, a); 3printf(“%d ”, a);
a++; }
}

37
Example: Memory: Output:
for (a=1;a < 5;a++) a 1
{ 4
1
2
3
5 2
3
printf("%d\n", a); 4
} end

printf(“end\n”);

38
Exercise:
 Write a program with for loop to print out the
following output:
5 10 15 20 25 30 35 40 45 50

Answer:

39
Examples
sum = 0; sum = 0;
i = 1; i = 1;
for ( ; i <= 10; i = i + 1) for ( ; i <= 10; )
{ {
sum = sum + i; sum = sum + i;
} i = i + 1;
printf("Sum = %d\n", sum); }
printf("Sum = %d\n", sum);

40
Example
sum = 0;
i = 1;
the empty for statement causes an endless loop.
for ( ; ; )
{
sum = sum + i;
i = i + 1;
}
printf("Sum = %d\n", sum);

41
Exercise:
 Write a program that Answer:
reads an integral, and use (Segment program)
a for loop to display series printf(“Please enter the limit:
of integers from 1 up to “);
the value. The output scanf(“%d”< &limit);
should be: For (i=1;

Please enter the limit : 3


1
2
3
42
Exercise:
d. Write a for loop to sum Answer:
up all the following
positive values

10 8 6 4 2 0 -2 -4
Total is 30

43
7.5.3 do-while Loop
It is a post-test loop.
If you want the loop’s body to execute at least 1 time,
you can use a do-while loop.

do
Actions {
action;
true
Condition
} while (condition);
false
44
Example:
char yesno;
do
{
printf("Hello world!\n");
printf("Print again (Y/N)? ");
while(getchar()!=‘\n’); // Clear the newline remains in buffer
scanf("%c", &yesno);
} while (yesno == 'Y' || yesno == 'y');
 

45
Exercise (a) and (b)
Convert the following loops to do-while loops. The
output should remain the same.

(a) Print the square of integers 1 to 10 inclusive.


number = 1; Answer:
while (number <= 10)
{
square = number * number;
printf("%d\n", square);
number++;
}
46
Exercise (a) and (b)
(b) Print all multiple of 3 in between 10 to 90 inclusive.
for (num = 10; num <= 90; num++)
if (num % 3 == 0)
Answer:
printf("%d\n", num);

47
7.6 Nested Loops
Loop within a loop.
Program logic gets more complicated.
When there is a nested loop, for each iteration of the
outer loop, the inner loop is entered and repeated
until done.

48
Example Memory: Output:
a
for(a=1; a < = 3; a++) * *
1
2
4
{ * *
* *
for(b = 1; b <=2; b++) b
{ 2
1
3

printf(“*”);
These loops continue the
} operation and produce
printf(“\n”); this output

49
7.7 Jump Statements
To terminate the loop or skip some statements within
a loop when certain condition is met.
Some controls of loop execution are needed.
2 types of jump statements:
 break statement
 continue statement

50
7.7.1 break Statement
Causes immediate exit from the structure .
Program execution continues with the first statement
after the structure.
It can be used in
while loop
for loop
do-while loop
switch statements

51
Example
int x;
for (x = 1; x <= 10; x++)
{
if (x == 5)
Output:
break; 1 2 3 4
printf("%d ",x); Loop ended at 5
}
printf("\nLoop ended at %d\n", x);

52
7.7.2 continue Statement
 A continue statement skip any remaining statements
in the body of the structure and proceeds with the
next iteration of the loop.

53
Example
int x;
for (x = 1; x <= 10; x++)
{
if (x == 5) Output:
continue; 1 2 3 4 6 7 8 9 10
printf("%d ",x); Loop ended at 11
}
printf("\nLoop ended at %d\n", x);

54

You might also like