SlideShare a Scribd company logo
1 of 54
CSWD1001
Programming Methods
Iteration or Repetition Structures
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
1
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
Condition Controlled
and
Count Controlled loops
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
3
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
Four Types of Repetition / Loop
•For
•While
•Do-while
•Nested loop
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
5
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
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
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
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
• 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
• 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
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
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
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
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
Flowchart of Repetition While
Condition Statement (s)
True
False
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
16
Example Use Case Repetition While
• Program to calculate one salesperson’s commission
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
17
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
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
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
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
Flowchart of Repetition Do-While
Condition
True
False
Statement (s)
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
22
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
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
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
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
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
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
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
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
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
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
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
Deciding Which Loop to Use
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
34
• 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
Values Increment, Decrement, User Input
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
36
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
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
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
Sentinels
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
40
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
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
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
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
Careful with Infinite Loop
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
45
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
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
Avoid Common Loop Mistake
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
48
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
Neglecting to Initialize the Loop Control
Variable
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
50
Neglecting to Alter the Loop Control Variable
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
51
Using the Wrong Comparison with the Loop
Control Variable
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
52
Including Statements Inside the Loop that
Belong Outside the Loop
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
53
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

More Related Content

What's hot

Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
Kumar
 

What's hot (20)

Decision making in JAVA
Decision making in JAVADecision making in JAVA
Decision making in JAVA
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Inheritance in OOPS
Inheritance in OOPSInheritance in OOPS
Inheritance in OOPS
 
Control structures in C
Control structures in CControl structures in C
Control structures in C
 
C lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareC lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshare
 
C# program structure
C# program structureC# program structure
C# program structure
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
Java if else condition - powerpoint persentation
Java if else condition - powerpoint persentationJava if else condition - powerpoint persentation
Java if else condition - powerpoint persentation
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstraction
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
stacks2
stacks2stacks2
stacks2
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
Control structure
Control structureControl structure
Control structure
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 

Similar to 5 Repetition Structures

Running Head SCM GLOBE SIMULATION7SCM Globe Simul.docx
Running Head SCM GLOBE SIMULATION7SCM Globe Simul.docxRunning Head SCM GLOBE SIMULATION7SCM Globe Simul.docx
Running Head SCM GLOBE SIMULATION7SCM Globe Simul.docx
jeanettehully
 
Business Canvas and SWOT Analysis For mo.docx
             Business Canvas and SWOT Analysis   For mo.docx             Business Canvas and SWOT Analysis   For mo.docx
Business Canvas and SWOT Analysis For mo.docx
hallettfaustina
 
Chapter 13 breakeven analysis
Chapter 13   breakeven analysisChapter 13   breakeven analysis
Chapter 13 breakeven analysis
Bich Lien Pham
 
Chapter 13 breakeven analysis
Chapter 13   breakeven analysisChapter 13   breakeven analysis
Chapter 13 breakeven analysis
Bich Lien Pham
 
AssumptionsAssumptionsPlant Capacity (megawatts)80Variable cost pe.docx
AssumptionsAssumptionsPlant Capacity (megawatts)80Variable cost pe.docxAssumptionsAssumptionsPlant Capacity (megawatts)80Variable cost pe.docx
AssumptionsAssumptionsPlant Capacity (megawatts)80Variable cost pe.docx
rock73
 

Similar to 5 Repetition Structures (20)

2 Program Design Methodology
2 Program Design Methodology2 Program Design Methodology
2 Program Design Methodology
 
4 Decision Structures and Boolean Logic
4 Decision Structures and Boolean Logic4 Decision Structures and Boolean Logic
4 Decision Structures and Boolean Logic
 
6 Function
6 Function6 Function
6 Function
 
7 Input Validation
7 Input Validation7 Input Validation
7 Input Validation
 
8 Array
8 Array8 Array
8 Array
 
Theory of production
Theory of productionTheory of production
Theory of production
 
Systems imlementation for Kasetsart University
Systems imlementation for Kasetsart University Systems imlementation for Kasetsart University
Systems imlementation for Kasetsart University
 
Discounted Cash Flow
Discounted Cash FlowDiscounted Cash Flow
Discounted Cash Flow
 
List of programs to practice for ICSE
List of programs to practice for ICSEList of programs to practice for ICSE
List of programs to practice for ICSE
 
Acc 543Enhance teaching / snaptutorial.com
Acc 543Enhance teaching / snaptutorial.comAcc 543Enhance teaching / snaptutorial.com
Acc 543Enhance teaching / snaptutorial.com
 
Advanced Computer Programming..pptx
Advanced Computer Programming..pptxAdvanced Computer Programming..pptx
Advanced Computer Programming..pptx
 
Running Head SCM GLOBE SIMULATION7SCM Globe Simul.docx
Running Head SCM GLOBE SIMULATION7SCM Globe Simul.docxRunning Head SCM GLOBE SIMULATION7SCM Globe Simul.docx
Running Head SCM GLOBE SIMULATION7SCM Globe Simul.docx
 
Monte-Carlo simulations - Kim BENNI @ ComRisk London May 2017
Monte-Carlo simulations - Kim BENNI @ ComRisk London May 2017Monte-Carlo simulations - Kim BENNI @ ComRisk London May 2017
Monte-Carlo simulations - Kim BENNI @ ComRisk London May 2017
 
Business Canvas and SWOT Analysis For mo.docx
             Business Canvas and SWOT Analysis   For mo.docx             Business Canvas and SWOT Analysis   For mo.docx
Business Canvas and SWOT Analysis For mo.docx
 
03b loops
03b   loops03b   loops
03b loops
 
Theory of production Production Function
Theory of production Production Function Theory of production Production Function
Theory of production Production Function
 
Chapter 13 breakeven analysis
Chapter 13   breakeven analysisChapter 13   breakeven analysis
Chapter 13 breakeven analysis
 
Chapter 13 breakeven analysis
Chapter 13   breakeven analysisChapter 13   breakeven analysis
Chapter 13 breakeven analysis
 
AssumptionsAssumptionsPlant Capacity (megawatts)80Variable cost pe.docx
AssumptionsAssumptionsPlant Capacity (megawatts)80Variable cost pe.docxAssumptionsAssumptionsPlant Capacity (megawatts)80Variable cost pe.docx
AssumptionsAssumptionsPlant Capacity (megawatts)80Variable cost pe.docx
 
L. E. Peabody & Associates, Inc. - Power Plant Financial Risk Assessment
L. E. Peabody & Associates, Inc. - Power Plant Financial Risk AssessmentL. E. Peabody & Associates, Inc. - Power Plant Financial Risk Assessment
L. E. Peabody & Associates, Inc. - Power Plant Financial Risk Assessment
 

Recently uploaded

MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MysoreMuleSoftMeetup
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
httgc7rh9c
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
EADTU
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 

Recently uploaded (20)

How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Ernest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell TollsErnest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell Tolls
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 

5 Repetition Structures

  • 1. CSWD1001 Programming Methods Iteration or Repetition Structures 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 1
  • 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
  • 3. Condition Controlled and Count Controlled loops 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 3
  • 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
  • 36. Values Increment, Decrement, User Input 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 36
  • 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
  • 40. Sentinels 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 40
  • 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

  1. 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.
  2. Explanation
  3. #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; }
  4. #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; }
  5. #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;}
  6. Modules can be called from statements in the body of a loop. Modularizing the code in a loop often improves the design.