Upload
wilfrid-preston
View
277
Download
11
Embed Size (px)
DESCRIPTION
Objectives Develop problems using loop logic structure with decision and sequential logic structures Use problem-solving tools (IPO Chart, Pseudocode, Flowchart) when developing solution using loop logic structure Use counters and accumulators in problem solution
Citation preview
Chapter 7Problem Solving with
Loops
CMPF144 Introduction to Problem Solving and Basic CMPF144 Introduction to Problem Solving and Basic ComputerComputer
ObjectivesObjectives1. Develop problems using loop logic structure
with decision and sequential logic structures2. Use problem-solving tools (IPO Chart,
Pseudocode, Flowchart) when developing solution using loop logic structure
3. Use counters and accumulators in problem solution
Objectives (Cont.)Objectives (Cont.)4. Distinguish different uses of two types of
loop logic structures5. Distinguish different uses of two loop
designs6. Use nested loop instructions to develop
problem solution7. Use recursion in simple problem
Loop Logic StructureLoop Logic Structure Also known as Repetition Control Structure Is used when we need to perform certain SAMESAME
actions REPEATEDLYREPEATEDLY Main DIFFICULTY: to identify which instructions should
be repeated Performing TWO (2)TWO (2) standard tasks:
Counting (incrementing @ decrementing) Accumulating ( calculating a sum @ total)
4
Loop Logic Structure Loop Logic Structure (Cont.)(Cont.) Can be categorized into TWO (2)TWO (2) main types:
While/End_While Repeat/Until
Each type of loop structure has a specific use according to language / problem
Each type of structure DO NOT share the same Pseudocode and Flow chart
5
Can be either INCREMENTINGINCREMENTING or DECREMENTINGDECREMENTING Incrementing is done by adding a constant, such as 1 or 2, to
the value of a variable Example: Decrementing is a process of subtracting a constant from a
current variable’s value Example: Variable names are the samesame on both sides of equal sign. Is a type of assignment instruction
i = i + 1
CountingCounting6
counter = counter - 2
AccumulatingAccumulating A process of summing up a group of numbers Similar to incrementing, except a variablevariable
instead of a constant is added to another variable
Example:
Is also a type of assignment instruction
7
total = total + numbernumber
While/End_WhileWhile/End_While
Using the keyword of WHILE…WHILE…THEN….END_WHILETHEN….END_WHILE
Tells the computer that while the condition is TRUETRUE, it should repeat ALL instructions between the WHILE and END_WHILE (loop)
8
While/End_While (Cont.)While/End_While (Cont.) Diamond is used for the whilewhile part, which represents
condition / decision Decision will be checked before executing any instructions
within the loop If resultant is FALSEFALSE at the start, the instructions within
the loop will NOT be executed If resultant is TRUETRUE, the complete set of instructions will be
executed, and computer will go back to the beginning of the loop and process the condition again, until it is FALSEFALSE
9
While/End_While (Cont.)While/End_While (Cont.) Pseudocode Flow Chart
10
Begin . . WHILE condition(s) THEN
Instruction Instruction
END_WHILE . .End
Exercise 1:Exercise 1:Develop an IPO chart, pseudocode, flowchart and complete Python program, to find the average age of all the students in a class
11
IPO ChartIPO Chart
Input Process Outputage 1. Get age
2. Calculate average3. Display average
average
12
BeginSet count = 0Set sum = 0.0Get ageWHILEWHILE age <> 0 THENTHENsum = sum + agecount = count + 1Get ageEND_WHILEEND_WHILEaverage = sum / countDisplay average
End
PseudocodePseudocode13
Tell me, Which one is:
•Primer Read??•Trip value @ flag??
Flow ChartFlow Chart14
TF
Set sum = 0.0
Begin
Set count = 0
count = count + 1
End
average = sum/count
Display average
Get age
age <> 0
sum = sum + age
Get age
sum = 0.0count = 0age = input("How old are you:")while age <> 0: sum = sum + age count = count + 1 age = input("How old are you:")average = sum/countprint "The average age is", average
Python CodePython Code15
Output:Output:
Repeat/UntilRepeat/Until
Using the keyword of REPEAT….UNTILREPEAT….UNTIL Tells the computer to repeat the set of
instructions between the Repeat and the Until, until a condition is TRUETRUE
16
Repeat/Until (Cont.)Repeat/Until (Cont.) TWO (2) TWO (2) major differences between Repeat/Until loop
with While/End_While loop: In While/End_While loop, program continues to loop as long as
resultant of condition is TRUETRUE. Whereas Repeat/Until loop continues to loop while resultant of condition is FALSEFALSE
In While/End_While loop, condition is processed at the BEGINNINGBEGINNING. However, in the Repeat/Until loop, the condition is processed at the ENDEND, which cause the instructions in the loop to be processed at least ONCE, regardless of whether it is necessary (hence, While/End_While is often the preferredpreferred choice)
17
Repeat/Until(Cont.)Repeat/Until(Cont.) Pseudocode Flow Chart
18
Begin . . REPEAT
Instruction Instruction
UNTIL condition(s) . .End
Exercise 2:Exercise 2: Refer back to same scenario case in Exercise 1 IPO chart is still the same Pseudocode and Flow chart is different as
compared to solution in Exercise 1
19
BeginSet count = 0Set sum = 0.0Get ageREPEATREPEATsum = sum + agecount = count + 1Get ageUNTIL UNTIL age == 0average = sum / countDisplay average
End
PseudocodePseudocode20
Flow ChartFlow Chart21
T
F
Set sum = 0.0
Begin
Set count = 0
count = count + 1
End
average = sum/count
Display average
Get age
age == 0
sum = sum + age
Get age
General Design of LoopGeneral Design of Loop
Two general designs: Automatic-counter loop Sentinel-controlled loop
22
Automatic-Counter LoopAutomatic-Counter Loop
Also known as counter-controlled loop Is used when we need to execute a number of
instructions from the program for a finite, pre-determined number of time
It incrementsincrements or decrementsdecrements a variable (which acts as a counter) each time the loop is repeated
23
The programmer uses a variable as a counter that starts counting at a specified number and increments the variable each time the loop is processed. Example:
The amount to be incremented is specified by the instruction. Example:
The set of instructions within the loop repeats until the counter is greater than greater than an ending number
count = 0
Automatic-Counter Loop Automatic-Counter Loop (Increments)(Increments)24
count = count + 2
Exercise 3:Exercise 3:Develop an IPO chart, pseudocode, flowchart and complete Python program, to find the average age of FIVE (5) users
25
IPO ChartIPO Chart
Input Process Outputage 1. Get age
2. Calculate average3. Display average
average
26
BeginSet count = 0Set sum = 0.0Get ageWHILEWHILE count < 4 THENTHENsum = sum + agecount = count + 1Get ageEND_WHILEEND_WHILEaverage = sum / countDisplay average
End
PseudocodePseudocode27
Flow ChartFlow Chart28
TF
Set sum = 0.0
Begin
Set count = 0
count = count + 1
End
average = sum/count
Display average
Get age
count< 4
sum = sum + age
Get age
sum = 0.0count = 0age = input(“Your age:")while count < 4: sum = sum + age count = count + 1 age = input(“Your age:")average = sum/countprint "The average age is", average
Python CodePython Code29
Output:Output:
The programmer uses a variable as a counter that starts counting at a specified number and increments the variable each time the loop is processed. Example:
The amount to be decremented is specified by the instruction. Example:
The set of instructions within the loop repeats until the counter is lesser than lesser than or not equal to not equal to an ending number
count = 10
Automatic-Counter Loop Automatic-Counter Loop (Decrements)(Decrements)30
count = count - 1
Exercise 4:Exercise 4:
Develop an IPO chart, pseudocode, flowchart and complete Python program, for a program which will prompt for the user to insert a positive integer. The program will then perform count down (decrement by ONE) towards the integer inserted. The message of “Happy New Year” will be displayed AFTER the integer is decreased to ZERO.
31
IPO ChartIPO Chart
Input Process Outputnumber 1. Get number
2. Display number until 03. Display “Happy New Year”
• Number• Message of
“Happy New Year”
32
BeginGet numberWHILEWHILE number >= 0 THENTHENDisplay numbernumber = number - 1END_WHILEEND_WHILEDisplay “Happy New Year”
End
PseudocodePseudocode33
Flow ChartFlow Chart34
T
F
Begin
number = number - 1
End
Display “Happy New Year”
Get number
Display number
number >= 0
number=input("Give me a number:")while number >= 0: print number number = number - 1print "Happy New Year"
Python CodePython Code35
Output:Output:
Sentinel-controlled LoopSentinel-controlled Loop
Is used when we need to execute a number of instructions from the program indefinitely until the user tells it to stop or a special condition is met
IndicatorIndicator (also known as flag, switches, trip values or sentinel values) needs to be set internally in the program to control when the processing of a loop should stop
36
Exercise 5:Exercise 5:
Develop an IPO chart, pseudocode, flowchart and complete Python program, for a program which will read in a series of student’s score (as long as the score is not -99). Upon receiving the sentinel value -99, the program will stop reading in students’ score. It will then compute and display average score for all students and the total number of students whom have inserted scores into program.
37
IPO ChartIPO Chart
Input Process Outputscore 1. Get score
2. Calculate average, count3. Display average, count
averagecount
38
BeginSet sum = 0.0Set count = 0Get scoreWHILEWHILE score <> -99 THENTHENsum = sum + scorecount = count + 1Get scoreEND_WHILEEND_WHILEaverage = sum / countDisplay average, count
End
PseudocodePseudocode39
Flow ChartFlow Chart40
TF
Set sum = 0.0
Begin
Set count = 0
count = count + 1
End
average = sum/count
Display average, count
Get score
score <> -99
sum = sum + score
Get score
Python CodePython Code41
Output:Output:
Why don’t you try to
code??
Nested LoopsNested Loops
Loops can be nested like decision logic structure Each inner loop must be nested inside the loop
just outside it (outer loop) However, both loops do NOT have to come from
the same type of loop structure Example:
A While/End_While Loop can be nested inside a Repeat/Until Loop
42
Exercise 6:Exercise 6:
Develop an IPO chart, pseudocode, flowchart and complete Python program, for a program which will prompt for two inputs from user:1.The number of multiplication timetables2.The number of rows required in each set of multiplication timetable The program will then generate a complete timetable set based on user’s requirement
43
IPO ChartIPO Chart
Input Process Outputnumberrow
1. Get set2. Get row3. Calculate multiply4. Display multiply
multiply
44
PseudocodePseudocode45
BeginGet numberGet rowset i = 1WHILEWHILE i <= number THENTHENSet j = 1WHILE WHILE j <= row THENTHENmultiply = i * jDisplay multiplyj = j + 1END_WHILEEND_WHILEi = i + 1Display “*******”
END_WHILEEND_WHILEEnd
Flow ChartFlow Chart46
It’s drawing time
47
Sample Output:Sample Output:
Let’s try to code
RecursionRecursion Occurs when a module or a function calls back
itself The condition that ends the loop must be
within the module Will be covered in lab module 7
48
More exercisesMore exercisespp.186, PROBLEMS
Question 1Question 3
49
Loop ChallengesLoop Challenges50
CONSTRUCT appropriate Pseudocode and Flow chart for each scenario case @ sample output provided
Then CONVERT each Pseudocode @ Flow chart into complete Python program
Loop Challenge - 1Loop Challenge - 151
Loop Challenge - 2Loop Challenge - 252
Loop Challenge - 3Loop Challenge - 353
Loop Challenge - 4Loop Challenge - 4
Develop a program to calculate how many years does it take for a user to get RM10000 in his saving account, assuming that he deposited RM5000 into a bank, with yearly interest 2.00%
54
55 Loop Challenge - Loop Challenge - 55
Loop Challenge - 6Loop Challenge - 656
Loop Challenge - 7Loop Challenge - 7 An applicant for a secretarial job will be given a
maximum of five typing tests. The applicant will be hired as soon as he or she scores over 50 words per minute on two tests. Write a program that allows a supervisor to enter each typing test score on completion of each test. The program should print Hire as soon as the applicant qualifies without asking for further tests. If after five test scores have been entered the typist still hasn’t qualified, the program should print reject.
57
58 Loop Challenge – 7 (cont.)Loop Challenge – 7 (cont.)
Loop Challenge – 8Loop Challenge – 859