What we’ll Learn:
Introduction to repetition structure
Condition-controlled loops – while, do while, and do-until
Count-controlled loops – for
Sentinels
Nested loops
Common programmer mistake
2. What we’ll learn
• Introduction to repetition structure
• Condition-controlled loops – while, do while, and do-until
• Count-controlled loops – for
• Sentinels
• Nested loops
• Common programmer mistake
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
2
4. Definition
• A condition controlled loop – uses a true/false
condition to control the number of times that it repeats
• A count controlled loop
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
4
5. Four Types of Repetition / Loop
•For
•While
•Do-while
•Nested loop
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
5
6. Repetition For
• Iterates a specific number of times
• Three actions will be perform in for loop
• Initialization
• Test
• Increment / Decrement
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
6
7. Declaration of Repetition For
For (int n = 5; n < 0; n++)
Statement
Statement
Statement
End for
Initialization Evaluate Increment
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
7
8. Flowchart of Repetition For
Counter
Evaluation
Statement (s)
True
False
Set counter = n
Counter
Increment/Decrement
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
8
9. Example Use Case Repetition For
• Your friend Amanda just inherited a European sports car from her uncle.
Amanda lives in the United States, and she is afraid she will get a speeding
ticket because the car’s speedometer works in kilometers per hour.
• She has asked you to write a program that displays a table of speeds in
kilometers per hour with their values converted to miles per hour. The
formula for converting kilometers per hour to miles per hour is:
MPH = KPH × 0.6214
• In the formula, MPH is the speed in miles per hour and KPH is the speed in
kilometres per hour.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
9
10. • The table that your program displays should show speeds from 60
kilometers per hour through 130 kilometers per hour, in increments of
10, along with their values converted to miles per hour. The table
should look something like this:
KPH MPH
60 37.284
70 43.498
80 49.712
Etc…
130 80.782
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
10
11. • After thinking about this table of values, you decide that you will write
a For loop that uses a counter variable to hold the kilometer-per-hour
speeds.
• The counter’s starting value will be 60, its ending value will be 130,
and a step value of 10 will be used.
• Inside the loop you will use the counter variable to calculate a speed in
miles-per-hour.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
11
12. Pseudocode
// Declare variables to hold speeds in MPH and KPH.
Declare Real mph
Declare Integer kph
// Display the table headings.
Display "KPH", Tab, "MPH"
Display "-----------------------"
// Display the speeds.
For kph = 60 To 130 Step 10
// Calculate the miles-per-hour.
Set mph = kph * 0.6214
// Display KPH and MPH.
Display kph, Tab, mph
End For
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
12
13. Flowchart
End
Declare
Real mph,
Integer kph
Display “KPH”, Tab,
“MPH”
Display “-------”
Set kph = 60
Kph < =
130
Setp mph = kph * 0.6214 Display kph, Tab, mph Add 10 to kph
Start
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
13
14. Repetition While
• A statement or set of statement to repeat as long as a condition is true
• The loop has two parts
• A condition that is tested for a true or false value
• A statement or set of statements that is repeated as long as the condition is true
• The while loop is known as pretest loop, which means it tests its
condition before performing an iteration; it will never execute if its
condition is false to start with
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
14
15. Declaration of Repetition While
While (condition)
Statement
Statement
Statement
End While
Body of the loop - Repeated while the
condition is true
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
15
16. Flowchart of Repetition While
Condition Statement (s)
True
False
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
16
17. Example Use Case Repetition While
• Program to calculate one salesperson’s commission
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
17
18. Pseudocode
// Variable declarations
Declare Real sales, commission
Declare String keepGoing = "y"
// Constant for the commission rate
Constant Real COMMISSION_RATE = 0.10
While (keepGoing == “y”)
// Get the amount of sales.
Display "Enter the amount of sales."
Input sales
// Calculate the commission.
Set commission = sales * COMMISSION_RATE
// Display the commission
Display "The commission is $", commission
Display "Do you want to calculate another"
Display "commission? (Enter y for yes.)"
Input keepGoing
End While
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
18
19. main()
Declare Real sales, commission
Declare String keepGoing = “y”
Constant Real COMMISION_RATE = 0.10
keepGoing
= “y”
Display “Enter the
amount of sales”
main()
Input sales
Set commission = sales *
COMMISIONS_RATE
Display “The
commission is “, $,
commision
Display “Do you
want to calculate
another”
Display
“commission?
(Enter y for yes)”
Input keepGoing
Flowchart
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
19
20. Repetition Do-While
• Do-while loop is post-test loop – means it performs an iteration before
testing its condition
• As the result, the do-while loop always performs at least one iteration,
even if its condition is false to begin with
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
20
21. Declaration of Repetition Do-While
Do
Statement
Statement
Statement
Etc.
While (condition)
Statement – always performed once,
and then repeated while the condition is true
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
21
22. Flowchart of Repetition Do-While
Condition
True
False
Statement (s)
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
22
23. Example Use Case Repetition Do-While
• Samantha owns an import business and she calculates the retail prices of her
products with the following formula:
Retail Price = Wholesale Cost × 2.5
• She has asked you to design a program to do this calculation for each item
that she receives in a shipment. You learn that each shipment contains
various numbers of items, so you decide to use a loop that calculates the
price for one item, and then asks her whether she has another item.
• The loop will iterate as long as she indicates that she has another item.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
23
24. Pseudocode
Module main()
// Local variable
Declare String keepGoing
// Calculate commissions as many times as
needed.
Do
//Display a salesperson's commission.
Call showCommission()
// Do it again?
Display "Do you want to calculate
another"
Display "commission? (Enter y for yes.)"
Input keepGoing
While (keepGoing == "y“)
End Module
// The showCommission module gets the
// amount of sales and displays the commission.
Module showCommission()
// Local variables
Declare Real sales, commission
// Constant for the commission rate
Constant Real COMMISSION_RATE =
0.10
// Get the amount of sales.
Display "Enter the amount of sales."
Input sales
// Calculate the commission.
Set commission = sales *
COMMISSION_RATE
// Display the commission
Display "The commission is $",
commission
End Module
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
24
25. Display “Do you
have another
item?(Enter y for
yes)”
Start
Declare String doAnother
doAnother
== “y”
OR
doAnother
== “Y”
showRetail()
Input doAnother
End
showRetail()
Declare Real wholesale,
retail Constant Real
MARKUP = 2.5
Display “Enter
an item’s
wholesale cost”
Input wholesale
Set retail = wholesaleCost
* MARKUP
Display “The
retail price is $”,
retail
Return
Flowchart
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
25
26. Another Example
Start
// Declare a variable to hold the password.
Declare String password
// Repeatedly ask the user to enter a password until the
// correct one is entered.
Do
// Prompt the user to enter the password.
Display "Enter the password."
Input password
// Display an error message if the wrong password was entered.
If password != "prospero" Then
Display "Sorry, try again."
End If
Until password == "prospero"
// Indicate that the password is confirmed.
Display "Password confirmed.“
End
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
26
27. Flowchart
Start
Declare String Password
Display “Enter the
password”
Input password
password!
=
“prospero”
Display “Sorry, try
again.”
password=
=
“prospero”
Display “Password
confirmed”
End
True
True
False
False
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
27
28. Repetition Nested
• A loop that is inside another loop is called a nested
loop.
• Outer loop - the loop that contains the other loop
• Inner loop - the loop that is contained is
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
28
29. Declaration of Repetition Nested While
While (condition)
Statement
Statement
While (condition)
Statement
Statement
Etc.
End While
End While
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
29
30. Example Use Case Repetition Nested
• Suppose you want to write a program that
produces quiz answer sheets like the ones
shown in right figure.
• Each answer sheet has a unique heading
followed by five parts with three questions in
each part, and you want a fill-in-the blank line
for each question.
• You could write a program that uses 63
separate output statements to produce three
sheets, but it is more efficient to use nested
loops.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
30
31. Pseudocode
Start
Declarations
string quizName
num partCounter, questionCounter
string QUIT = "ZZZ"
num PARTS = 5
num QUESTIONS = 3
string PART_LABEL = "Part "
string LINE = ". ______“
housekeeping()
while (quizName <> QUIT)
detailLoop()
Endwhile
endOfJob()
End
housekeeping()
output "Enter quiz name or ", QUIT, "to quit "
input quizName
Return
detailLoop()
output quizName
partCounter = 1
while (partCounter <= PARTS)
output PART_LABEL, partCounter
questionCounter = 1
while (questionCounter <= QUESTIONS)
output questionCounter, LINE
questionCounter = questionCounter + 1
Endwhile
partCounter = partCounter + 1
Endwhile
output "Enter next quiz name or ", QUIT, " to quit "
input quizName
Return
endOfJob()
Return
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
31
32. Flowchart
Start
Declarations
String quizName
Num partCounter,
questionCounter
String QUIT = “ZZZ”
Num PARTS = 3
Num QUESTIONS = 3
String PART_LABEL = “Part”
String LINE = “.___”
housekeeping()
quizNa
me <>
QUIT?
detailLoop()
endOfJob()
End
Housekeeping()
Display “Enter quiz name or”, QUIT, “to
quit”
Input quizName
Return
endOfJob()
Return
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
32
33. detailLoop()
Output quizName
parCounter = 1
partCoun
ter <=
PARTS?
Display “Enter next quiz name or” , QUIT,
“to quit”
Input quizName
Return
Output PART_LABEL, partCounter
questionaCounter = 1
questionC
ounter <=
QUESTIO
NS?
Output questinCounter, LINE
questionCounter = questionCounter + 1
partCounter = parConter + 1
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
33
34. Deciding Which Loop to Use
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
34
35. • Use the While loop to repeat a task as long as a condition is true
• The While loop is ideal in situations where the condition might be false to start
with, and in such cases you do not want the loop to iterate at all.
• The Do-While loop is also a candidate in situations where a task must
be repeated as long as a condition is true.
• It is the best choice, however, when you always want the task to be performed
at least once, regardless of whether the condition is true or false to start with.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
35
37. Values Increment, Decrement, User Input
• Increment / decrement
• Ability to increment/decrement the counter variable by any value
you wish
• User input
• Let the user decide the number of times that a loop should iterate
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
37
38. Declaration
Declare Integer counter = startingValue
While (counter <= maxValue)
Statement
Statement
Statement
Etc
Set counter = counter + 1
End While
Initialize a counter variable to the
starting value
Compare the counter to the maximum
value
Add 1 to the counter variable during
each iteration
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
38
39. Example Use Case Repetition Values
Increment, Decrement, User Input
// Variables
Declare Integer counter, square,
Declare lowerLimit, upperLimit
// Get the lower limit.
Display "This program displays numbers and"
Display "their squares. What number should"
Display "I start with?"
Input lowerLimit
// Get the upper limit.
Display "What number should I end with?"
Input upperLimit
// Display table headings.
Display "Number", Tab, "Square"
Display "-----------------------"
// Display the numbers and their squares.
For counter = lowerLimit To upperLimit
// Calculate number squared.
Set square = counter^2
// Display number and number squared.
Display counter, Tab, square
End For
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
39
41. Definition
• A sentinel is a special value that marks the end of a list
of values
• A sentinel value must be unique enough that it will not
be mistaken as a regular value in the list. When a
program reads the sentinel value, it knows it has
reached the end of the list, so the loop terminates.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
41
42. Example Use Case Sentinels
• The county tax office calculates the annual taxes on property using the following formula:
Property Tax = Property Value × 0.0065
• Every day, a clerk in the tax office gets a list of properties and has to calculate the tax for
each property on the list. You have been asked to design a program that the clerk can use
to perform these calculations.
• In your interview with the tax clerk, you learn that each property is assigned a lot number,
and all lot numbers are 1 or greater.
• You decide to write a loop that uses the number 0 as a sentinel value. During each loop
iteration, the program will ask the clerk to enter either a property’s lot number, or 0 to
end.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
42
43. Pseudocode
Module main()
// Local variable for the lot number
Declare Integer lotNumber
// Get the first lot number.
Display "Enter the property's lot number"
Display "(or enter 0 to end)."
Input lotNumber
// Continue processing as long as the user does not enter lot number 0.
While (lotNumber ! = 0)
// Show the tax for the property.
Call showTax()
Get the next lot number.
Display "Enter the lot number for the next property (or 0 to end)."
Input lotNumber
End While
End Module
// The showTax module gets a property's value and displays its tax.
Module showTax()
// Local variables
Declare Real propertyValue, tax
// Constant for the tax factor.
Constant Real TAX_FACTOR = 0.0065
// Get the property's value.
Display "Enter the property's value."
Input propertyValue
// Calculate the property's tax.
Set tax = propertyValue * TAX_FACTOR
// Display the tax.
Display "The property's tax is $", tax
End Module
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
43
44. Flowchart
End
Declare
Real propertyValue, tax
Constant Real
TAX_FACTOR = 0.0065
Display “Enter the
property’s Lot number (or
enter 0 to end)”
Input lotNumber
lotNum
ber !=0
showTax()
Start
Display “Enter the lot
number fro the next property
(or 0 to end)”
Input lotNumber
showTax()
Declare integer lotNumber
Display “Enter the property
value”
Input propertyValue
Set tax = propertyValue *
TAX_FACTOR
Display “The property’s tax
is $”, tax
Return
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
44
45. Careful with Infinite Loop
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
45
46. Definition
• If a loop does not have a way of stopping, it is called
an infinite loop
• An infinite loop continues to repeat until the program
is interrupted.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
46
47. Example
// Variable declaration
Declare Real sales, commission
Declare String keepGoing = “y”
// Constant for the commission rate
Constant Real COMMISSION_RATE = 0.10
// Warning infinite loop
While keepGoing == “y”
// Get the amount of sales
Display “Enter the amount of sales.”
Input sales
//Calculate the commission
Set commission = sales * COMMISSION_RATE
// Display the commission
Display “The commission is $”, commission
End While
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
47
48. Avoid Common Loop Mistake
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
48
49. Common Mistake
• Neglecting to initialize the loop control variable
• Neglecting to alter the loop control variable
• Using the wrong comparison with the loop control variable
• Including statements inside the loop that belong outside the
loop
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
49
50. Neglecting to Initialize the Loop Control
Variable
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
50
51. Neglecting to Alter the Loop Control Variable
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
51
52. Using the Wrong Comparison with the Loop
Control Variable
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
52
53. Including Statements Inside the Loop that
Belong Outside the Loop
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
53
54. Summary
• When you use a loop in a computer program, you can write one set of
instructions that operates on multiple, separate sets of data.
• Three steps must occur in every loop: You must initialize a loop control
variable, compare the variable to some value that controls whether the loop
continues or stops, and alter the variable that controls the loop.
• When you must use loops within loops, you use nested loops. When nesting
loops, you must maintain two individual loop control variables and alter
each at the appropriate time.
• Common mistakes that programmers make when writing loops include
neglecting to initialize the loop control variable, neglecting to alter the loop
control variable, using the wrong comparison with the loop control variable,
and
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
54
Editor's Notes
Initialization: before the loop begins, the counter variable is initialized to a starting value. The starting value that is used will depend on the situation
Test: the loop tests the counter variable by comparing it to a maximum value. If the counter variable is less than or equal to the maximum value, the loop iterates. If the counter is greater than the maximum value, the program exits the loop.
Increment: to increment a variable means to increase its value. During each iteration, the loop increments the counter variable by adding 1 to it.
Explanation
#include <iostream>
using namespace std;
int main(){
int sales, commission = 0;
string keepGoing = "y";
int commissionRate = 0.10;
while (keepGoing == "y")
{
cout << "Enter the amount of sales: ";
cin >> sales;
cout << sales << endl;
commission = sales * commissionRate;
cout << "The commission is $ " << commission << endl;
cout << "Do you want to calculate another commission (Enter y for yes): ";
cin >> keepGoing;
}
return 0;
}
#include <iostream>
using namespace std;
int showRetail();
int main()
{
string doAnother = "y , Y";
do{
showRetail();
cout << "Do you have another item? (Enter y for yes): ";
cin >> doAnother;
}while(doAnother == "y" or doAnother == "Y");}
int showRetail(){
int wholeSale, retail;
int markUp = 2.50;
cout << "Enter an item's wholesale cost: ";
cin >> wholeSale;
retail = wholeSale * markUp;
cout << "The retail price is $ " << retail << endl;
}
#include <iostream>
using namespace std;
int main(){
string password = "prospero";
do{
cout << "Enter the password: ";
cin >> password;
if (password != "prospero")
{
cout << "Sorry, try again.";
}
cout << "The password is correct.";
}while(password == "prospero");
return 0;}
Modules can be called from statements in the body of a loop.
Modularizing the code in a loop often improves the design.