TOPIC 4: REPETITION CONTROL STRUCTURE...2. The loop condition is evaluated. If the loop condition...
Transcript of TOPIC 4: REPETITION CONTROL STRUCTURE...2. The loop condition is evaluated. If the loop condition...
LOGO
REPETITION CONTROL
STRUCTURE
CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING
1
LOGOContents
Introduction 1
for loop2
while loop3
do … while loop4
2
LOGOIntroduction
It is used when a statement or a block of
statements need to be executed several
times.
Programmers use the repetition structures,
referred to more simply as a loop, when they
need the computer to repeatedly process one
or more program instructions until some
condition is met, at which time the repetition
structures end.
Repetition is also known as iteration or loop.
3
LOGOIntroduction
Two types of loop:
Pretest loop• Evaluation occurs before the instructions within the
loop are processed
• Instruction may never be processed
•while statement, for statement
Posttest loop• Evaluation occurs after the instructions within the loop
are processed
• Instructions will be processed at least once
•do..while statement
4
LOGOIntroduction
Repeat sequence of instruction many
times (as long as condition is TRUE )
Repetition = iteration = loop
Similar function, different names
Example
You have to create a simple program that will
receive 5 integer inputs from user. Sum those
5 inputs and calculate the average.
Check out the C++ code with and without
looping
5
LOGOIntroduction
A program that will receive 5 integer inputs
from user and sum those 5 inputs and
calculate the average./*
Problem: Sum 5 numbers, calculate the average,
display the results
*/
int num1, num2, num3, num4, num5;
int sum;
float average;
cin>>num1>>num2>>num3>>num4>>num5;
sum = num1 + num2 + num3 + num4 + num5;
average = sum / 5;
cout<<"Sum: "<<sum<<"\tAverage: "<<average;
Is this what
you are
thinking???
6
LOGOIntroduction
The correct way by using repetition
int num, sum = 0, count = 0;
float average;
while(count < 5)
{
cout<<"Num "<<(count + 1)<<": ";
cin>>num;
sum = sum + num;
count = count + 1;
}
average = sum / 5;
cout<<"Sum: "<<sum<<"\tAverage: "<<average;
Solution
using
looping!!!
7
LOGOTypes of Repetition Statement
Types of repetition
for
while
do…while
8
LOGOTypes of Repetition Structure
Types of repetition structure
Counter-controlled repetition• Number of repetition is fixed (known in advance)
• e.g. repeat a process 10 times
Sentinel-controlled repetition• Stop looping whenever a special value is entered
• e.g. enter -1 to end the loop
Flag-controlled repetition• When a defined value is matched, it stops looping, else loop
will continue
• e.g. looping will continue 1000 times, however it will stop immediately if the value entered by user matches with ID = 102
9
LOGORequirements of Repetition
/* example using while loop */
int i = 0; //initialize
while(i < 10)
{
statements;
i++;
}Loop Body
Loop Control
Variable
(LCV)
Loop
Condition
10
LOGORequirements of Repetition
/* example using for loop */
for(i = 0; i < 10; i++)
{
statements;
}
Loop Body
Loop Control
Variable
(LCV)
Loop
Condition
11
LOGORequirements of Repetition
12
Loop Control Variable (LCV)
A variable whose value determines whether
the loop body will be executed or not
It has initial value and increment/decrement
value
Loop Condition
If the condition is true, the loop body is
executed; if condition is false the loop exits
Loop Body
A block of statements to be repeated
LOGORequirements of Repetition
Execution of loop body is controlled by 3
operations:
Initialization of the LCV
Evaluation of LCV in the loop condition
Update of the LCV by incrementing (e.g. x++) or decrementing (e.g. x--)
13
LOGORequirements of Repetition
Increment operator
14
Common
statement
Equivalent to
x++ x = x + 1 x += 1
- x = x + 3 ?
- ? x += 5
- x = x + i ?
Table 4.1: Increment operator
LOGORequirements of Repetition
Decrement operator
15
Common
statement
Equivalent to
x-- x = x - 1 x -= 1
- x = x - 9 ?
- ? x -= 2
- ? x -= sum
Table 4.2: Decrement operator
LOGOIntroduction – example
Let say, you want to display “ I love C++”5 times.
I love C++
I love C++
I love C++
I love C++
I love C++
void main()
{
cout << “ I love c++!\n”;
cout << “ I love c++!\n”;
cout << “ I love c++!\n”;
cout << “ I love c++!\n”;
cout << “ I love c++!\n”;
}
16
LOGO
The idea of using a loop…
Introduction – example
Pseudocode
Begin
Repeat
output “I love C++”End
Flow Chart
I love C++
QUESTION:HOW DO WE STOP THE LOOP???
17
LOGO
Adding a loop control variable
Introduction – example
Pseudocode
Begin counter = 1
Repeat (if counter <= 5)
output “I love C++”counter ++
End
Variable counter is LCV
Flow Chart
I love C++
counter = 1
counter <=
5
counter ++
T
F
18
LOGOIntroduction – loop control variable
A LCV controls the number of times the
statement or the block of statements is
being executed.
Pseudocode
Begin
counter = 1
Repeat (if counter <= 5)
output “I love C++”counter ++
End
Flow Chart
I love C++
Counter = 1
Counter
<= 5
Counter ++
T
F
19
LOGOIntroduction
Requirement of a repetition structure
Flow Chart
I love C++
Counter = 1
Counter
<= 5
Counter ++
T
F
Initialize
LCV
Evaluate
LCV (loop condition)
Loop body
Update
LCV20
LOGOIntroduction
Task associated with loop:
Counter – to determine number of items.
• Is done by adding a constant, such as 1 or 2, to
the value of a variable.
Accumulator – to find totals.
• Is done by adding a variable to another variable.
counter = counter + 1
sum = sum + variable
21
LOGOIntroduction
Indicator – value use to end the loop
Counter
control
Indicators
Sentinel
control
While(counter<=5)
Counter control
sentinel=999;
While(number!=sentinel)
sentinel control22
LOGO
The for loop
23
LOGOfor loop
Also called as a counted or indexed for
loop
The general form of the for statement is:
The initial statement, loop condition, and update statement are called for loop
control statements
Items in square brackets ([ ]) are optional.
for ([initial statement]; loop condition; [update statement])
statement;
24
LOGOfor loop
The for loop executes as follows:
1. The initial statement executes.
2. The loop condition is evaluated. If the loop condition
evaluates to true
i. Execute the for loop statement.
ii. Execute the update statement (the third expression
in the parentheses).
3. Repeat Step 2 until the loop condition evaluates to false.
The initial statement usually initializes a variable.
In C++, for is a reserved word.
for ([initial statement]; loop condition; [update statement])
statement;
25
LOGOfor loop – Example 1
Example : Displaying the numbers 1
through 3
for (int count = 1; count <= 3; count = count + 1)
cout << count << endl;
initialization condition update
Result:
1
2
3
26
LOGOfor loop – Example 1
Using for loop to display ‘Welcome to
C++’.
Pseudocode:
Start
For( set i to 1; i less than or equal to 3; add 1 to i)
display “welcome to C++”Endfor
End
27
LOGOfor loop – Example 1
Flowchart Start
i = 0
i <= 10
Display “welcome
to C++”
i ++
End
T
F
28
LOGOfor loop – Example 1
29
LOGOfor loop – Example 2
Example: to create a program to display
backward the first 10 non negative
number.
30
LOGOfor loop – Exercises
Exercise 1: create a program that display
the first 10 positive odd integers.
31
LOGOfor loop – Exercises
Exercise 1 - answer
32
LOGOfor loop – Exercises
Exercise 2: how many time the following
loop processed?
Answer:
for (int count = 6; count < 6; count = count + 1)
cout << count << endl;
33
LOGOfor loop – Exercises
Exercise 3: how many time the following
loop processed?
Answer:
for (int count = 4; count <= 10; count = count + 2)
cout << count << endl;
34
LOGOfor loop – Example 3
Example: to calculate and display total of
3 numbers
35
LOGOfor loop – Example 3
Pseudocode:
Start
Initialize total = 0
For(set counter to 1; counter less than or
equal to 3; add 1 to counter)
input number
total = total + number
Endfor
Display total
End
36
LOGOfor loop – Example 3
Flowchart Start
counter=1, total = 0,
for
counter
<= 3
Input
number
total = total + number
counter = counter + 1
Output
total
End
F
T
37
LOGOfor loop – Example 3
C++ program segment
total = 0;
for (int count = 1; count <= 3; count = count + 1)
{
cin>>number;
total = total + number;
}
cout << “total:” <<total<<endl;
38
LOGOfor loop – Exercises
Exercise 4: Suppose j, sum, and num are int
variables, and the input values are 26, 34, 61, 4,
and -1. What is the output of the code below?
cout << "Enter a number : ";cin >> num;
for (j = 1; j <= 4; j++){
sum = sum + num;cout << "Enter a number : ";
cin >> num;}cout << sum << endl;
39
LOGOfor loop – Exercises
Exercise 4: answer
40
LOGOfor loop
A semicolon at the end of the forstatement (just before the body of the loop) is a semantic error. In this case, the action of the for loop is empty.
In the for statement, if the loop condition is omitted, it is assumed to be true.
In a for statement, you can omit all three statements—initial statement, loop condition, and update statement. The following is a legal for loop:
41
LOGOfor loop
This is an infinite loop, continuously printing the word Hello
for (;;)
cout << "Hello" << endl;
42
LOGO
The while loop
43
LOGOwhile loop
Repeat or loop as long as the condition is
true.
The general form of the while statement
is:
while is a reserved word.
Statement can be simple or compound
while (expression)
{
statement;
}
44
LOGOwhile loop
Expression acts as a decision maker and
is usually a logical expression
Statement is called the body of the loop
The parentheses are part of the syntax
while (expression)
{
statement;
}
45
LOGOwhile loop
Expression provides an entry condition
statement executes if the expression initially
evaluates to true
loop condition is then reevaluated
statement continues to execute until the
expression is no longer true
while (expression)
{
statement;
}
46
LOGOwhile loop
Infinite loop
continues to execute endlessly
can be avoided by including statements in the
loop body that assure exit condition will eventually be false
47
LOGOwhile loop
The general form of while loop flowchart:
48
LOGOwhile loop
Example: to display the first five positive
integers which increment by five.
49
LOGOwhile loop
Pseudocode:
Begin
Initialize i to 0
While i is less than or equal to 20
Display i
add 5 to I (update)
End while
End
50
LOGOwhile loop
Enter the while statement
i <= 20
Expression evaluates to zero
False condition
Expression evaluates to a nonzero number
True condition
Go back and reevaluate the expression
LoopDisplay
i
i = i + 5
i = 0
Start
End
51
LOGOwhile loop
Example C++ program segment:
i = 0;
while ( i <= 20)
{
cout << i << “ “;i = i + 5;
}
1) Loop Control
Variable (LCV)
2) A starting point / Initialization of the LCV
3) Testing the loop repetition
condition
4) Updating the LCV
52
LOGOwhile loop
Various form of while loops:
Counter controlled
Sentinel controlled
Flag controlled
53
LOGOwhile loop – counter control
If you know exactly how many pieces of data need to be read, the while loop
becomes a counter-controlled loop.
General syntax:
54
LOGOwhile loop – counter control
Counter controlled while loop includes the following:
◦ Counter
A numeric variable used for counting something
◦ Accumulator
Numeric variable used for accumulating something
◦ Initializing
Assign a beginning value to the counter or
accumulator; typically 0
◦ Updating
Also called incrementing, means adding a number to
the values stored in the counter or accumulator
55
LOGOwhile loop – counter control
Example
#include <iostream>
#include <conio>
int main()
{
int count;
count = 1;
while (count <= 10)
{
cout << count << endl;
count++;
}
getch();
return 0;
}
initializing
updating
56
LOGOwhile loop – counter control
Problem: Create a program that displays
the word ‘Hello’ on the screen 10 times.
Solution:
Psedocode
Begin
Initialize lcv to 0
While lcv is less than 10
Display “Hello”Update lcv
End while
End
57
LOGOwhile loop – counter control
Flowchart
Begin
Initialize
counter = 0
counter < 10 Helloupdate
counter T
F
End
58
LOGOwhile loop – counter control
Program and output
int main(){
int count;
count = 0;
while (count < 10){
cout << "Hello" << endl;count++;
}
getch();return 0;
}
59
LOGOwhile loop – counter control
Exercise: Write a C++ statement
associated to the following flowchart.
Begin
Initialize
counter = 10
counter < 100 Display counter
Multiplied by 2
Add 10 to
counter
T
F
End
60
LOGOwhile loop – counter control
Program and output
int main()
{
int count;
count = 10;
while (count < 100)
{
cout << count * 2 << endl;
count += 10;
}
getch();
return 0;
}
61
LOGOwhile loop – sentinel control
A sentinel-controlled while loop uses a
special value called sentinel to control
the loop.
Sentinel value is a special value that indicates
the end of a set of data or of a process
Sentinel variable is tested in the condition
and loop ends when sentinel is
encountered
62
LOGOwhile loop – sentinel control
General syntax :
63
LOGOwhile loop – sentinel control
Example #include <iostream>#include <conio>
int main(){
char answer;
cout << "Do you want to quit (Y - yes, N - no) : ";cin >> answer;
while (answer != 'Y'){
cout << "Welcome to the program." << endl;cout << "Do you want to quit (Y - Yes, N - No) : ";cin >> answer;
}cout << "Bye.";
getch();return 0;
}
Sentinel value
64
LOGOwhile loop – sentinel control
Output screen
65
LOGOwhile loop – sentinel control
Exercise: to create a program that process
the loop as long as user enter an even
number
66
LOGOwhile loop – sentinel control
Solution
Flowchart
Begin
End
number % 2 == 0Get another
number
F
Prompt for
a number
Get
a number
T
67
LOGOwhile loop – sentinel control
Program
int main(){
int number;
cout << "Enter a number : ";cin >> number;
while (number % 2 == 0){cout << "Enter the next number : ";cin >> number;
}
cout <<"You have entered an odd number to terminate”<<“the program.";
getch();return 0;
}
68
LOGOwhile loop – sentinel control
Output
69
LOGOwhile loop – flag control
A flag-controlled while loop uses a
bool variable to control the loop
The flag-controlled while loop takes the
form:
70
LOGOwhile loop – flag control
Example
void main()
{
bool found = false;
char continues;
while (!found)
{
cout << " Program continued..still want to continue"
<< " the loop? Press Y for yes, N for No"<< endl;
cin>>continues;
if(continues == ‘Y’)found = false;
else
found = true;
}
cout << "Program terminated";
getch();
}
71
LOGO
The do … while loop
72
LOGOdo … while loop
The general form of a do...while
statement is:
The statement executes first, and then the
expression is evaluated.
If the expression evaluates to true, the
statement executes again
As long as the expression in a do...while statement is true, the
statement executes
do
statement
while (expression);
73
LOGOdo … while loop
General form of flowchart:
74
LOGOdo … while loop
To avoid an infinite loop, the loop body
must contain a statement that makes the expression false
The statement can be simple or
compound. If compound, it must be in
braces
do...while loop has an exit condition
and always iterates at least once (unlike for and while)
75
LOGOdo … while loop
Example: to display the first five positive
integers which increment by five.
76
LOGOdo … while loop
Pseudocode:
Begin
Initialize i to 0
do
Display i
add 5 to I (update)
While i is less than or equal to 20
End
77
LOGOdo … while loop
Flowchart
Enter do statement
i <= 20
Expression evaluates to zero
False condition
Expression evaluates to a nonzero number
True condition
Go back and reevaluate the expression
Loop
Display
i
i = i + 5
i = 0
Start
End
78
LOGOdo … while loop
C++ program segment
i = 0;
do
{
cout << i << “ “;i = i + 5;
}
while ( i <= 20);
79
LOGOdo … while loop
Exercise 1
a. The while loop produces nothing.b. The do..while loop outputs the number 11 and also
changes the value of i to 16.
80
LOGOdo … while loop
Exercise 2 – determine the output of the
following program
int x = 20;
do
{
cout << x << endl;
x = x – 4;
}
while (x > 10)
81
LOGOdo … while loop
Exercise 3 – determine the output of the
following program
int x = 1;
do
{
cout << x << endl;
x = x + 1;
}
while (x < 5)
82
LOGOdo … while loop
Exercise 4 – determine the output of the
following program
int total = 1;
do
{
cout << total << endl;
total = total + 2;
}
while (total >=3)
83
LOGOdo … while loop
Answer: INFINITE LOOP!
84
LOGO
Nested Control Structures
85
LOGONested loop
In many situations, it is very convenient to
have a loop contained within another loop.
Such loops are called nested loops.
For each single trip, through the outer
loop, the inner loop runs through its entire
sequence.
Each time counter i increases by 1, the inner
loop executes completely.
86
LOGONested loop
Example of C++ program segment
for (i = 0; i <= 5; i++)
{
cout << "\n i is now " << i << endl;
for (j = 1; j <= 4; j++)
cout << " j = " << j ;
}
87
LOGONested loop
How it works…
i is now 0
j = 1 j = 2 j = 3 j = 4
i is now 1
j = 1 j = 2 j = 3 j = 4
i is now 2
j = 1 j = 2 j = 3 j = 4
i is now 3
j = 1 j = 2 j = 3 j = 4
i is now 4
j = 1 j = 2 j = 3 j = 4
i is now 5
j = 1 j = 2 j = 3 j = 4
Outer loopInner loop
88
LOGONested loop
Suppose we want to create the following
pattern.
In the first line, we want to print one star,
in the second line two stars and so on.
*
**
***
****
*****
89
LOGONested loop
Since five lines are to be printed, we start
with the following for statement.
for (i = 1; i <= 5 ; i++)
The value of i in the first iteration is 1, in
the second iteration it is 2, and so on
Can use the value of i as limit condition in
another for loop nested within this loop to
control the number of starts in a line.
90
LOGONested loop
The syntax
for (i = 1; i <= 5 ; i++)
{
for (j = 1; j <= i; j++)
cout << "*";
cout << endl;
}
91
LOGONested loop
What pattern does the code produce if we replace the first for statement with the following?
for (i = 5; i >= 1; i--)
Answer:
*****
****
***
**
*92
LOGO
The jump statements
93
LOGObreak
Causes an exit from loop or switch
statementvoid main()
{
int x;
for (x = 1; x<=10; x++)
{
if (x == 5)
break;
cout<< x <<“”;
}
cout<< “ loop terminated at x:”<<x<<endl;
}
1 2 3 4 loop terminated at x: 5
Press any key to continue 94
LOGOcontinue
Skips the remaining statements in the loop
and proceed with the next loopvoid main()
{
int x;
for (x = 1; x<=10; x++)
{
if (x == 5)
{
a=x;
continue;
}
cout<< x <<“”; }
cout<< “ the number”<<a<<endl;cout<< “ is not printed”<<endl;
}
1 2 3 4 6 7 8 9 10 the number 5 is not printed
Press any key to continue 95
LOGO
www.themegallery.com
96