[go: up one dir, main page]

0% found this document useful (0 votes)
10 views51 pages

Chap06 - Looping

Uploaded by

black hello
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views51 pages

Chap06 - Looping

Uploaded by

black hello
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 51

C++ Programming:

Problem Solving and


Programming
Chapter 6
Repetition
Objectives
In this chapter you will:
• Learn about repetition (looping) control
structures
• Explore how to construct and use count-
controlled, sentinel-controlled, flag-controlled,
and EOF-controlled repetition structures
• Examine break and continue statements
• Discover how to form and use nested control
structures
2
Concept of Looping

• A loop is a group of
instructions the
computer executes
repeatedly while
some looping
continuation
condition remain
TRUE.

3
4
Pre-Test Loop
• The condition is
checked at the false
beginning of each Condition
iteration (loop)
true

Actions

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

6
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

7
Post-test Loop

• The condition is checked


Actions at the end of each loop

true
Condition

false

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

9
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

10
Exercise
• Based on the general algorithms above, what
will happen to each type of loops if the box is
initially empty?

11
Loop Condition, Initialization
& Update
• Other than condition, commonly there are 2
more processes (initialization and updating)
associate with loops.

12
Loop Condition, Initialization &
Update
Initialization
Set student counter = 1

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

Updating

This loop will repeat for 3 times

13
Loop Condition, Initialization &
Update
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).

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

16
Event-Controlled Loop

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

While response = “Yes”


Print total

17
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).

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

19
Looping Control Structures

• 3 types:
−while loops
−for loops
−do-while loops

20
while loops
• It is a pre-test and
event-controlled loop. false
Condition
• Action is run repeatedly
while the condition is true true
• Syntax: Actions

while (condition)
{ The braces { and } can be
action ignored if there is only 1
statement in the body of a
} while loop.
21
while loop - Example
• Write a program that finds the value of 2
multiply itself 10 times by using a while
statement.

22
while loop - Example
#include <iostream>
using namespace std;
int main() Initialization
{
int x = 2;
int count = 1;
Condition
while (count <= 10)
{
x = x * 2;
count++; Updating
}

cout << "The result is “<< x;

return 0; } 23
while loop – Exercise
• Write a loop to print out the even numbers from
500 to 2.

Answer:
Algorithm
set counter to 500 int i=500;
while counter >= 2 while(i>=2)
print counter value {
subtract 2 from counter cout << i << endl;
end while
i-=2;
}
24
while loop – Exercise
Answer:
• Write a loop to
int x=2, count=1, sum=0;
print the sum
double average;
and average of
even numbers while(x<=10) {
from 2 to 10. sum = sum + x;
x+=2; // same as x=x+2;
count += 1;
}
average = sum / count;
cout <<“ sum: ”<<sum << endl;
cout << “average:”<<average;
25
Sentinel Value
• Sentinel value is a special value that causes
a loop to stop
• It cannot confuse with the valid value,
example: -999 for a test score
• Used when user may not know how many
values to be entered during input process

26
Sentinel Value - Example

AACS2524 Programming Concepts 27


for loop
• It is a pre-test and expr1
(Initialization)
counter-controlled loop
•Syntax : expr2
False

(Condition)
Initialization Condition True

Action
for ( expr1; expr2; expr3 )
expr3
{ (condition)
action
} Updating

28
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.

29
for loop is equivalent to
while loop
• Used when a loop is
for (expr1; expr2; expr3) to be executed a
{ known / fixed
action number of times.
} We can do the same
thing with a while
expr1; loop, but the for loop
while (expr2) is easier to read and
{ more natural for
action; counter-controlled
expr3; loops.
}
30
for loop is equivalent to
while loop

for loop while loop

for (i = 1; i <= 10; i+ i = 1;


+) while (i <= 10)
{ {
cout << i; cout << i;
} i++;
}

31
for loop
The empty for statement causes
an endless loop

for ( ; ; )
{
action;

The loop can start but no condition tells


when to end the loop
32
for loop - Exercise
• Write a for loop to print the following integers
in sequence:
5 10 15 20 25 30 35 40 45 50

Answer:
for ( i = 5; i <= 50, i+=5 )
cout << i << ‘ ’;

33
for loop - Exercise
• Write a program that Answer:
reads a number, and
int limit;
use a for loop to
cout << “Please enter the
display series of limit : ";
integers from 1 up to cin << limit;
the number. The
output should be:
for (i = 1; i <= limit; i++)
Please enter the limit : 3 {
1 cout << i << endl;
2 }
3
34
do-while loop
• It is a post-test and event-controlled 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
35
do-while loop – Exercise
• 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;
while (number <= 10)
{
square = number * number;
cout << square << ‘ ’;
number++;
}
36
do-while loop – Exercise
Answer:
number = 1;
do {
square = number * number;
cout << square << ‘ ’;
number ++;
} while (number <= 10);

37
do-while loop – Exercise

(b) Print all multiple of 3 in between 10 to 90 inclusive.


for (num = 10; num <= 90; num++)
{
if (num % 3 == 0)
{
cout << num << ‘ ’;
}
}

38
do-while loop – Exercise
Answer:
num = 10;
do {
if (num % 3 == 0)
cout << num << ‘ ’;
num ++;
} while (num <= 90);

39
Loop used to
Accumulate Total

• An accumulator is a variable that you use to


gather or accumulate values.
• Important: Accumulator has initial value.
Usually it starts with 0.
Total Sales

Product 1: 120
Product 2: 250
Product 3: 360
Product 4: 99

Total: 829
40
Loop used to
Accumulate Total
• Example:
int total = 0, price;

for(int i = 0; i<4; i++) accumulat


{ or
cout << "Product " << i+1 << ": -> ";
cin >> price;
total = total + price;
}

cout << "\n\nTotal: " << total << endl;


41
Nested Loop
• 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 before the next outer loop
is entered.

42
Nested Loop - Example
for(i=0; i<3; i++)
Output: {
i=0: 1 2 3 4 5 cout<<“i=”<<i<<‘: ’;
i=1: 1 2 3 4 5
for(j=1; j<=5; j++)
i=2: 1 2 3 4 5 cout << j;

cout << endl;


}

43
Nested Loop – Exercise
• Use nested for loop to Answer:
print the pattern below: for (i = 0; i <= 3; i++)
@@@@@ {
for (j = 0; j <= 4; j++)
@@@@@
cout << ‘@’;
@@@@@
@@@@@ cout << endl;
}

44
Nested Loop – Exercise
• Without using the aid of computer, produce the output
of the following code:

int i, j;
for (i = 1; i <= 3; i++)
{
cout<<"Outer “<<i<<endl;
for (j = 1; j <= i; j++)
{
cout<<"Inner “<<j;
cout<<endl;
}
}

45
Nested Loop – Exercise
• What is the output for the following code?
for(int x = 0; x < 4; x++)
{
for(int y = 0; y <= x; y++)
{
cout << “+” ;
}
cout << endl;
}

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

47
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 statement

48
break statement - Example

int x;
for (x = 1; x <= 10; x++)
{
if (x == 5)
break;
cout << x;
}
cout<<“\nLoop ended at ”<<x<<“\n”;

49
continue statement
 A continue statement will skip any remaining
statements in the body of the structure and
proceeds with the next iteration of the loop.
• It can be used in
− while loop
− for loop
− do-while loop

50
continue statement - Example

int x;
for (x = 1; x <= 10; x++)
{
if (x == 5)
continue;
cout << x;
}
cout<<“\nLoop ended at ”<<x<<“\n”;

51

You might also like