59
Chapter 7 Problem Solving with Loops CMPF144 Introduction to Problem Solving and Basic CMPF144 Introduction to Problem Solving and Basic Computer Computer

Chapter 7 Problem Solving with Loops

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

Page 1: Chapter 7 Problem Solving with Loops

Chapter 7Problem Solving with

Loops

CMPF144 Introduction to Problem Solving and Basic CMPF144 Introduction to Problem Solving and Basic ComputerComputer

Page 2: Chapter 7 Problem Solving with Loops

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

Page 3: Chapter 7 Problem Solving with Loops

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

Page 4: Chapter 7 Problem Solving with Loops

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

Page 5: Chapter 7 Problem Solving with Loops

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

Page 6: Chapter 7 Problem Solving with Loops

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

Page 7: Chapter 7 Problem Solving with Loops

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

Page 8: Chapter 7 Problem Solving with Loops

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

Page 9: Chapter 7 Problem Solving with Loops

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

Page 10: Chapter 7 Problem Solving with Loops

While/End_While (Cont.)While/End_While (Cont.) Pseudocode Flow Chart

10

Begin . . WHILE condition(s) THEN

Instruction Instruction

END_WHILE . .End

Page 11: Chapter 7 Problem Solving with Loops

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

Page 12: Chapter 7 Problem Solving with Loops

IPO ChartIPO Chart

Input Process Outputage 1. Get age

2. Calculate average3. Display average

average

12

Page 13: Chapter 7 Problem Solving with Loops

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??

Page 14: Chapter 7 Problem Solving with Loops

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

Page 15: Chapter 7 Problem Solving with Loops

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:

Page 16: Chapter 7 Problem Solving with Loops

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

Page 17: Chapter 7 Problem Solving with Loops

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

Page 18: Chapter 7 Problem Solving with Loops

Repeat/Until(Cont.)Repeat/Until(Cont.) Pseudocode Flow Chart

18

Begin . . REPEAT

Instruction Instruction

UNTIL condition(s) . .End

Page 19: Chapter 7 Problem Solving with Loops

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

Page 20: Chapter 7 Problem Solving with Loops

BeginSet count = 0Set sum = 0.0Get ageREPEATREPEATsum = sum + agecount = count + 1Get ageUNTIL UNTIL age == 0average = sum / countDisplay average

End

PseudocodePseudocode20

Page 21: Chapter 7 Problem Solving with Loops

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

Page 22: Chapter 7 Problem Solving with Loops

General Design of LoopGeneral Design of Loop

Two general designs: Automatic-counter loop Sentinel-controlled loop

22

Page 23: Chapter 7 Problem Solving with Loops

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

Page 24: Chapter 7 Problem Solving with Loops

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

Page 25: Chapter 7 Problem Solving with Loops

Exercise 3:Exercise 3:Develop an IPO chart, pseudocode, flowchart and complete Python program, to find the average age of FIVE (5) users

25

Page 26: Chapter 7 Problem Solving with Loops

IPO ChartIPO Chart

Input Process Outputage 1. Get age

2. Calculate average3. Display average

average

26

Page 27: Chapter 7 Problem Solving with Loops

BeginSet count = 0Set sum = 0.0Get ageWHILEWHILE count < 4 THENTHENsum = sum + agecount = count + 1Get ageEND_WHILEEND_WHILEaverage = sum / countDisplay average

End

PseudocodePseudocode27

Page 28: Chapter 7 Problem Solving with Loops

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

Page 29: Chapter 7 Problem Solving with Loops

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:

Page 30: Chapter 7 Problem Solving with Loops

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

Page 31: Chapter 7 Problem Solving with Loops

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

Page 32: Chapter 7 Problem Solving with Loops

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

Page 33: Chapter 7 Problem Solving with Loops

BeginGet numberWHILEWHILE number >= 0 THENTHENDisplay numbernumber = number - 1END_WHILEEND_WHILEDisplay “Happy New Year”

End

PseudocodePseudocode33

Page 34: Chapter 7 Problem Solving with Loops

Flow ChartFlow Chart34

T

F

Begin

number = number - 1

End

Display “Happy New Year”

Get number

Display number

number >= 0

Page 35: Chapter 7 Problem Solving with Loops

number=input("Give me a number:")while number >= 0: print number number = number - 1print "Happy New Year"

Python CodePython Code35

Output:Output:

Page 36: Chapter 7 Problem Solving with Loops

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

Page 37: Chapter 7 Problem Solving with Loops

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

Page 38: Chapter 7 Problem Solving with Loops

IPO ChartIPO Chart

Input Process Outputscore 1. Get score

2. Calculate average, count3. Display average, count

averagecount

38

Page 39: Chapter 7 Problem Solving with Loops

BeginSet sum = 0.0Set count = 0Get scoreWHILEWHILE score <> -99 THENTHENsum = sum + scorecount = count + 1Get scoreEND_WHILEEND_WHILEaverage = sum / countDisplay average, count

End

PseudocodePseudocode39

Page 40: Chapter 7 Problem Solving with Loops

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

Page 41: Chapter 7 Problem Solving with Loops

Python CodePython Code41

Output:Output:

Why don’t you try to

code??

Page 42: Chapter 7 Problem Solving with Loops

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

Page 43: Chapter 7 Problem Solving with Loops

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

Page 44: Chapter 7 Problem Solving with Loops

IPO ChartIPO Chart

Input Process Outputnumberrow

1. Get set2. Get row3. Calculate multiply4. Display multiply

multiply

44

Page 45: Chapter 7 Problem Solving with Loops

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

Page 46: Chapter 7 Problem Solving with Loops

Flow ChartFlow Chart46

It’s drawing time

Page 47: Chapter 7 Problem Solving with Loops

47

Sample Output:Sample Output:

Let’s try to code

Page 48: Chapter 7 Problem Solving with Loops

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

Page 49: Chapter 7 Problem Solving with Loops

More exercisesMore exercisespp.186, PROBLEMS

Question 1Question 3

49

Page 50: Chapter 7 Problem Solving with Loops

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

Page 51: Chapter 7 Problem Solving with Loops

Loop Challenge - 1Loop Challenge - 151

Page 52: Chapter 7 Problem Solving with Loops

Loop Challenge - 2Loop Challenge - 252

Page 53: Chapter 7 Problem Solving with Loops

Loop Challenge - 3Loop Challenge - 353

Page 54: Chapter 7 Problem Solving with Loops

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

Page 55: Chapter 7 Problem Solving with Loops

55 Loop Challenge - Loop Challenge - 55

Page 56: Chapter 7 Problem Solving with Loops

Loop Challenge - 6Loop Challenge - 656

Page 57: Chapter 7 Problem Solving with Loops

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

Page 58: Chapter 7 Problem Solving with Loops

58 Loop Challenge – 7 (cont.)Loop Challenge – 7 (cont.)

Page 59: Chapter 7 Problem Solving with Loops

Loop Challenge – 8Loop Challenge – 859