Sei sulla pagina 1di 175

PROGRAMMING

Problem Solving

Edited by awie
What will you learn?
Problem Solving

Steps in Problem Design a


problem solving analysis (IPO) solution

Problem Identify IPO Algorithm Control


analysis structure

Design a Definition Sequence Selection Repetition


solution

implementation Flowchart if while

Testing pseudocode if else do while

documentation Nested if else for


Learning Outcome
• List five steps in problem solving
• Identify IPO from a given problem
• Define algorithm
• Solve a given problem using algorithm
• Apply appropriate control structure in problem
solving
Steps in problem solving
4

 Problem Analysis
 Design a solution
 Implementation
 Testing
 Documentation
Steps in problem solving
5

Problem Analysis
 Identify input, processing, output and data
component.
 Refer to book and website
 Ask expert
 Meet with system analyst and users.
Steps in problem solving
6

Design a solution
 Divide all program activities into program
modules.
 Create solution algorithm (pseudocode and
flowchart) for each program modules.
 Design user interface.
Steps in problem solving
7

Implementation
 Coding a program involves translating the solution
algorithm into programming language usually on
paper.
 Typing the code into the computer using
programming language such as Pascal, C++ and
Visual Basic.
Steps in problem solving
8

Testing
 Several methods have been devised for finding and removing
logic error and syntax error.
 Manually testing with sample data.
 The program is running through a computer using a
translator program. Before the program runs, it must be
free of syntax errors. Such errors will be identified by the
translator.
 Testing by a selected group of potential users. Potential
users try out the program and provide feedback.
Steps in problem solving
9

Documentation
 Documentation is important for people who may involve
with the program in the future.
 Other programmers wish to update and modify it (program
maintenance).
 Activities:
 Produce a description of the program, layouts out the
input and output records and program listing.
 Produce a problem definition, flowchart and pseudocode.
Steps in problem solving
10

Documentation
 Activities:
 Write comments with the program code
(internal documentation). These comments
explain the program’s purpose of the code
statements with the program.
Problem Analysis (IPO)
To do the IPO Analysis, start with identify :
1- Output
2- Input
3- Process
Problem Analysis (IPO)
How to make a hot coffee

Output : HOT COFFEE


Problem Analysis (IPO)
How to make a hot coffee?

hot water sugar coffee

INPUT
Problem Analysis (IPO)
How to make a hot coffee
Process
1. Add HOT WATER +
SUGAR + COFFEE in a
cup
2. Stir to blend the
coffee and sugar
together.
Problem Analysis (IPO)
 Output :
should answer the following question:
What does the user want to see printed
on the printer, displayed on the screen,
or stored in a file?
Problem Analysis (IPO)
 Input :
should answer the following question:
What information will the computer need to
know to print, display, or store the output
items?
Problem Analysis (IPO)
 Process :
Processing item:
An intermediate value that the algorithm
uses when processing the input into the
output
Input, Process, Output Analysis
18

 The IPO is used to analyze problems and develop


algorithms
 Used to organize and summarize the results of a
problem analysis
 It shows where in the solution the processing takes
place
Input, Process, Output Analysis
19

It can be represented using IPO chart.


Input Process Output
Input, Process, Output Analysis
20

It also can be represented using IPO analysis.

INPUT :
PROCESS :
OUTPUT :
Input, Process, Output Analysis
21

Example 1: Calculate the area of a rectangle


Identify :
To do the IPO Analysis,
start with:
INPUT : 1 – Output
PROCESS : 2 – Input
OUTPUT : 3 – Process
Input, Process, Output Analysis
22

Problem statement:
Calculate the area of a rectangle
width

height

We can summarize the information contained in the


problem statement as follows:
Input, Process, Output Analysis
23

Example 1: Calculate the area of a rectangle


Input: width, height

Process:
Calculate the area of rectangle.

Output: area of rectangle


Input, Process, Output Analysis
24

Example 1: Calculate the area of a rectangle


The Problem Analysis, can be represented using IPO
(Input, Processing, Output) Chart
Input Process Output
width Calculate the area of area of rectangle
height rectangle
Input, Process, Output Analysis
25

Problem statement:
Find the average of three numbers input by user
We can summarize the information contained in
the problem statement as follows:
Input, Process, Output Analysis
26

Example 2. Find the average of three numbers input by user


Input: num1,num2,num3

Process: calculate the average of three


numbers

Output:average of three numbers


Input, Process, Output Analysis
27

Example 2. Find the average of three numbers input by user


IPO (Input, Processing, Output) Chart
Input Process Output
Num1 Calculate average average
Num2
Num3
Input, Process, Output Analysis
28

Problem statement:
Find the average of area for two different
rectangular.
width2

width1
height2
height1
Input, Process, Output Analysis
29

Example 3. Find the average of area for two different


rectangular.
Input: width1,height1
width2, height2
Process: calculate average area of rec1 and
rec2
Output: average area of rec1 and rec2
Input, Process, Output Analysis
30

Example 3. Find the average of area for two different


rectangular.
IPO (Input, Processing, Output) Chart
Input Process Output
Input, Process, Output Analysis
31

Problem statement:
Determine the total cost of apples, given the
number of kilos of apples purchased and the
cost of apples per kilo

We can summarize the information contained in


the problem statement as follows
Input, Process, Output Analysis
32

Example 4. Determine the total cost of apples, given the number


of kilos of apples purchased and the cost of apples per kilo

Input: Number of kilos of apples


Cost of apples per kilo

Process: Calculate total cost of apples.

Output: total cost of apples


Input, Process, Output Analysis
33

Example 4. Determine the total cost of apples, given the number


of kilos of apples purchased and the cost of apples per kilo

IPO (Input, Processing, Output) Chart


Input Process Output
numOfKilo Calculate the total cost total cost
costPerKilo
Design a solution: Algorithm
 The algorithm is the abstract idea of solving a
problem.
 An algorithm is a step-by-step instructions that
will transform the input into the output
 It can be represent using pseudocode or flow
chart
Algorithm
 can be described using three control structures
(Bohm and Jacopini-1966);
 A Sequence
 is a series of statements that execute one after another
 A Selection – (branch)
 statement is used to determine which of two different
statements to execute depending on certain conditions
 A Looping – (repetition)
 statement is used to repeat statements while certain conditions
are met
Algorithm
 Techniques to represent the algorithms;
1. Pseudocode
2. Flowchart
Pseudocode Flow chart
• Artificial, informal language used to • Graphical representation of an
develop an algorithm. algorithm.
• A list of instructions. • Graphically shows the logic in a
• Language which human can solution algorithm.
understand. Similar to everyday • Special-purpose symbols connected
English by arrows (flow lines)
Algorithm
 How to make a mug of hot coffee:
Start
1. Boil water
2. Prepare a mug
3. Put a tea spoon of coffee &sugar
5. Pour hot water
6. Stir
End
Planning the algorithm
1. Do Problem Analysis
Identify:
INPUT :
PROCESS:
OUTPUT:
2. Transfer to pseudo code or flow chart
3. a. Must start with a start
b. Must close with an end
Pseudocode
 Statements are the 1
1 sentences in
English
START
statement 1
pseudocode. 2
statement 2
 It can be found from END

the ‘process’ inside the


IPO chart. 3
Flow chart
start
The
statements statement1
refers to any
input, output statement1
& process
involved end
Flow chart
41

Graphic Symbol Name Meaning

Terminal Symbol indicates the beginning and end points of an


(capsule) algorithm

Process Symbol shows an instruction other than input, output or


(rectangle) selection

Input-Output Symbol shows an input or output operation


(parallelogram)
Flow chart
42

Graphic Symbol Name Meaning

Disk Storage Input- indicates input from or output to disk storage


Output Symbol
(cylinder)

Printer Output Symbol shows hardcopy printer output

Decision / shows a selection process for two-way selection


Selection Symbol
(diamond)
Flow chart
43

Graphic Symbol Name Meaning

Flow Lines (arrow) indicates the logical sequence of execution steps in


the algorithm

Off-Page provides continuation of a logical path on another


Connector page

On-Page provides continuation of a logical path at another


Connector (circle) point in the same page
Example 5
44

Problem statement:
Calculate the area of a rectangle
Remember!
1. Do Problem Analysis
2. Transfer to pseudo code or flow chart
Example 5
45

1. IPO analysis

Input: width, height


Process: Calculate the area of rectangle
Output: display area of rectangle
Example 5
46

2. (a) Pseudocode
START
1. read width and height
2. calculate area
area of rectangle = width * height
3. output area of rectangle
END
Example 5: IPO and pseudocode
Input Process Output
width Calculate the area of rectangle area of rectangle
height
Algorithm - Pseudocode:

START

1. input width and height

2. Calculate area of rectangle


area of rectangle = width * height

3. Output area of rectangle

END
Example 5: Flow chart
48

2. (b) Flowchart start

Read width, height

areaOfRectangle = width*height

Output areaOfRectangle

end
Example 6
49

Problem statement:
Find the average of three numbers input by user
Remember!
1. Do Problem Analysis
2. Transfer to pseudo code or flow chart
Example 6
50

1. IPO analysis

Input:
Process:
Output:
Example 6
51

Find the average of three numbers input by user


2. (a) Pseudocode
START

Statement (s)

END
Example 6: IPO with pseudocode
Input Process Output
number1 Calculate the average of three numbers. average
number2
number3 Algorithm – Pseudocode:
START

1. Input number1, number2, number3

2. Calculate average
average = (number1 + number2 + number3) / 3

3. Output average
END
Example 6
53

Find the average of three numbers input by user


2. (b) Flowchart
Example 7
54

Problem statement:
Determine the total cost of apples, given the number of kilos of
apples purchased and the cost of apples per kilo

Remember!
1. Do Problem Analysis
2. Transfer to pseudo code or flow chart
Example 7
55

1. Problem Analysis

Input:
Process:
Output:
Example 7
Determine the total cost of apples, given the number of kilos of
apples purchased and the cost of apples per kilo
2. (a) Pseudocode
START

Statement (s)

END
Example 7
57

Determine the total cost of apples, given the number of kilos of


apples purchased and the cost of apples per kilo

2. (b) Flowchart
Design a Solution: Control structure
 Design a Solution
 Control Structure
Sequence
Selection
Repetition
Learning Outcome
 Explain the purpose of each control structure
 Apply appropriate control structure in problem
solving
Control structure
 Control structure is a method that allows the
programmer to control the flow of a program.
 Consist of three basic control structure:
 Sequence

 Selection

 Repetition
Control structure
 These structures are referred to as “control structure”
because they control the flow of the program’s logic.
 Using these structure makes a program or an algorithm
 Easy to understand
 Easy to debug

 Easy to change
Control Structure
is a series of statements that execute one after another
 Sequence
 is a series of statements that execute one after another
 Selection – (branch)
 statement is used to determine which of two different
statements to execute depending on certain conditions
 Looping – (repetition)
 statement is used to repeat statements while certain conditions
are met
Control Structure: Sequence
 Purpose of sequence control structure
 To solve the simplest programs consist just sequence of
statements.
 No loops, no selection amongst alternative actions, no use of
subroutines.
Control Structure: Sequence
 Instruction are executed sequentially one by one.
 The instructions execute from first to next, till the last
instruction. Then the program will terminate.

Last
1st Next … instruction
instruction instruction
Control Structure: Sequence

 Example 1 : What do you do in the morning?


 Brush teeth

 Wash face

 Comb hair

 Smile in mirror

 Having breakfast
Control Structure: Sequence
Example 2 :What would you do if you want to refuel your
car?
 Go to a petrol station.
 Remove nozzle from the fuel pump
 Insert nozzle in fuel tank
 Fill tank with fuel
 Replace nozzle at the fuel pump
 Pay for the fuel
 Leave petrol station
Control Structure: Sequence
Example 3 : Write the algorithm to get robot seated
on the chair
Control Structure: Sequence
 Example 8
PSZ Corporation gives a bonus to Irfan based on his
sales. Assume your program needs to calculate Irfan’s
bonus. The bonus is 5 percents of the sales
Example 8
69

Problem statement:
Calculate Irfan’s bonus. The bonus is 5% of the sales.

Remember!
1. Do Problem Analysis
2. Transfer to pseudo code or flow chart
Example 8
70

Calculate Irfan’s bonus. The bonus is 5% of the sales.

1. IPO Analysis:
Input: sales

Process: calculate bonus

Output: bonus
Example 8
Calculate Irfan’s bonus. The bonus is 5% of the sales.
2. (a) Pseudocode
START
1. input sales
2. calculate bonus
bonus = sales*0.05
3. output bonus
END
Example 8: IPO with pseudocode
Input Process Output
sales Calculate bonus bonus

Algorithm - Pseudocode:

START

1. input sales

2. Calculate bonus
bonus = sales*0.05

3. Output bonus

END
Example 8: Flow chart
73

2. (b) Flowchart start

Read sales

bonus = sales*0.05

Output bonus

end
Control Structure: Sequence
 Example 9
Tile Limited wants a program that allow its sales clerk
to enter width and length of area (feet), and also
price of square foot of tile. The program will display
the total price of tile based on the area inserted by
user.
Example 8
75

Problem statement:
program that allow its sales clerk to enter width and length of area (feet), and
also price of square foot of tile. The program will display the total price of tile
based on the area

Remember!
1. Do Problem Analysis
2. Transfer to pseudo code or flow chart
Example 9
76

1. IPO Analysis: program that allow its sales


Input: width, length, price clerk to enter width and
length of area (feet), and also
Process: calculate total price price of square foot of tile.
The program will display the
Output: total price total price of tile based on the
area.
Example 9
2. (a) Pseudocode
program that allow its sales
clerk to enter width and
START length of area (feet), and also
1. input width,length,price
price of square foot of tile.
2. calculate totalprice
totalprice = width*length*price The program will display the
3. output totalprice total price of tile based on the
END area.
Example 9: IPO with pseudocode
Input Process Output
width Calculate totalprice totalprice
length
price Algorithm - Pseudocode:

START

1. input width,length,price

2. Calculate totalprice
totalprice = width*length*price

3. Output totalprice

END
Example 9: Flow chart
79

2. (b) Flowchart start

Read width, length, price

totalprice = width*length,price

Output totalprice

end
Example 10
Melissa works for Quality Builders. Melissa's current weekly
pay is RM1000 but she is scheduled to receive a 3% raise
next week. Melissa wants you to write a program that will
display on the computer screen the amount of her new
weekly pay.
Example 10
81

Problem statement:

Remember!
1. Do Problem Analysis
2. Transfer to pseudo code or flow chart
Example 10
82

1. Problem Analysis

Input:
Process:
Output:
Example 10
2. (a) Pseudocode

START

Statement (s)

END
Example 10
84

2. (b) Flowchart
Try yourself
 APM Industry management asks you to create a
program that calculate the total overtime payment
for staff if overtime rate payment was given RM
5.00 per hour.
 The program will receive 2 numbers as input.
Calculate the sum of the 2 numbers
Control structure: Selection
86

ANALOGY
You need to choose to make
“Coffee O” or “Milk Coffee”
SUGAR
MILK
Control structure: Selection
 Purpose of selection
 Allows instructions to be executed non-sequentially.
 Allows the comparison of two expressions, and based
on the comparison, to select certain course of action

 The process needs you to make decision which action


you choose to perform
Control structure: Selection
88

Types of selection structure

if if-else nested if switch

FOCUS
Control structure: Selection if
if structure’s form
if (condition)
statement_1
If structure’s explanation
if condition is true
Perform action (statement_1 execute)
if condition is false, action is skipped, program
continues
Control structure: Selection if
90

Example 11: If student’s grade is greater than or equal


to 60 Print “Passed”

If the condition/expression is true


print statement executed and program goes on to next
statement
If the condition/expression is false
print statement is ignored and the program goes on to the next
statement or end program.
Control structure: Selection if
91

Pseudocode format:
start
if (condition/expression)
statement1
End
Control structure: Selection if
Flow chart format:
start

condition/expre false
ssion
true
statement1

end
Control structure: Selection if
Example 12
Print “Excellent!” when user enter marks greater than
and equal to 80.
Remember to plan your algorithm!
1. Do IPO Analysis
2. Transfer to Pseudocode or Flow Chart
Example 12
94

1. IPO Analysis
Input: mark

Process: Identify if mark greater and equal than 80,


then print “Excellent”

Output: “Excellent”
Example 12
95

2(a) Pseudocode

start
1. read mark
2. if (mark >= 80)
2.1 print “Excellent”
end
Example 12
start
2(b) Flow chart
Read mark
false
mark >= 80
true
Print “Excellent”

end 96
Control structure: Selection if else
if-else structure’s form • In this form, the condition is
if (condition/expression) first evaluated.
• If it evaluates to TRUE,
statement_1
statement_1 is executed.
else • Otherwise, statement_2 is
statement_2 executed.
• Either statement_1 or
statement_2 is executed but
not BOTH.
Control structure: Selection if else
98

Pseudocode format:
Start
……..
if (condition/expression)
statement_1
else
statement_2
……..
End
Control structure: Selection if else
Flow chart format:
start

condition/expre false
ssion
* All statements can be true statement2
input, processing or statement1
output

end
Control structure: Selection if else
100

1. IPO Analysis:

Input: mark
Process: Identify mark greater than and equal to 80 then print
statement
Output: “Excellent!” or “Sorry, try again”
Control structure: Selection if else
2(a) Pseudocode
start
1. read marks
2. if (marks >= 80)
2.1 print “Excellent”
Else
2.2 print “Sorry, try again”
end
Control structure: Selection if else
2(b) Flow chart start

Read mark
false
Mark>=80
true Print “sorry,
Print “Excellent” try again”

end
Control structure: Selection if else
103

 Example 14:
A high school poetry competition is open only for
students above 15 years old. Display “Eligible” if
the students meet the requirement, else display “Not
eligible” if otherwise.
Control structure: Selection if else
Example 14
A high school poetry competition is open only for students above 15 years old.
Display “Eligible” if the students meet the requirement, else display “Not eligible”
if otherwise.

Remember to plan your algorithm!


1. Do IPO Analysis
2. Transfer to Pseudocode or Flow Chart
Selection if else
105

1. IPO Analysis:

Input: age
Process:
Identify either the age of students greater than 15
Output: “Eligible” or “Not eligible”
Selection if else
106

 2(a)Pseudocode
start
1. read age
2. if (age > 15)
2.1 print “Eligible”
else
2.2 print “Not eligible”
end
Selection if else
107

 2(b) Flow chart start

Read age
false
age>15
true Print “Not
Print “eligible” eligible”

end 107
Try yourself

 Write IPO, pseudocode and draw a flowchart


to enter a number and if the number is 0,
print “number is zero”.
 The program will receive 2 numbers as input.
Calculate the sum of the 2 numbers
Multiple selection (nested if)
109

 The if-else structure can also be nested to


any depth.
 Nested if-else structure test for multiple cases
by placing if-else selection structure inside if-
else selection structure
Multiple selection (nested if)
 It must undergo two or more conditions.
 The situation shows that you have to fulfill the general condition
(outer if) before you move to the specific condition (inner if)
 You have to fulfill the first condition before you can proceed to
another condition.
Multiple selection (nested if)
Pseuducode format:
START
if (expression1)
{
if (expression2)
statement2;
else
statement1;
}
else
last statement;
END
Multiple selection (nested if)
Flow chart format:
start
true true
expression1 expression2

false statement2
false
* All statements can be statement1
input, processing or Last statement
output
end
Multiple selection (nested if)
Example 1:

Write the IPO, pseudocode and draw a flowchart


to determine if the age less or equal to 19 and
points less than 6 print OK, if points larger than 6
print Test, else print Review.
Multiple selection (nested if)
114

1. IPO Analysis:

Input: age, point


Process:
Determine if the age is less or equal to 19 and
point less than 6
Output: “ok” or “Test” or “Review”
Multiple selection (nested if)
115

 2(a) Pseudocode
start
1.read age, point
2. if (age <= 19)
2.1 if (point < 6)
2.1.1 print “ok”
2.2. else
2.2.1 print “Test”
3. Else
3.1 print “Review”
end
Multiple selection (nested if)
2(b) Flow chart format:
start

Read age, input


true true
(age<=19) point < 6
false false Print “ok”
Print “Test”
Print “Review”

end
Multiple selection (if - else )
117

 The multiple if-else if structured takes the general form:

if (expression_1)
statement_1;
else if (expression_2)
statement_2;
else if (expression_3)
statement_3;
else
statement_4;
Multiple selection (if else)
Flow chart format:
start
true true
expression1 statement1
false
expression2 statement2
false
* All statements can be
input, processing or expression3 statement2
output
end
Multiple selection (if - else )
119

 In this nested form, expression_1 is evaluated. If it evaluates to


(TRUE), statement_1 is executed.
 If not, control goes to the second if, where expression_2 is
evaluated. If it evaluates to (TRUE), statement_2 is executed.
 If not, control goes to the third if, where expression_3 is
evaluated. If it evaluates to (TRUE), statement_3 is executed.
 If not, statement_4 is executed.
 Rules  Only ONE of the statements is executed.
Multiple selection (if - else )
120

 Example 1:
if student’s grade is greater than or equal to 80
Print “A”
else if student’s grade is greater than or equal to 60
Print “B”
else if student’s grade is greater than or equal to 50
Print “C”
else
Print “Failed”
Multiple selection (if - else )
121

1. IPO Analysis:
Input: grade
Process: To compare the grade based on the condition value
Output: “A” or “B” or “C” or “Failed”
Multiple selection (if - else )
122

 2(a) Pseudocode start


1.read grade
2. if (grade >= 80)
2.1print “A”
3. else if (grade >= 60)
3.1 print “B”
4. else if (grade >= 50)
4.1 print “C”
5. else
5.1print “Failed”
end
Multiple selection (if - else )
123

 2(b) Flow chart start

read grade
true
grade >= 80 print“A”
false
true
grade >= 60 print“B”
false true
grade >= 50 print“C”
false
Print “Failed”

end 123
Multiple selection (if - else )
124

 Example 2:
if (x > 0)
display "x is positive"
else if (x < 0)
display "x is negative"
else
display "x is 0"
Multiple selection (if - else )
125

1. IPO Analysis:

Input: x

Process: To identify whether the value of x is greater than 0,


less than 0 or equal 0.

Output: “x is positive“ or "x is negative“ or “x is 0”


Multiple selection (if - else )
126

 2(a) Pseudo code


start
1. read x
2. if (x > 0)
2.1 display "x is positive"
3. else if (x < 0)
3.1 display "x is negative"
4. else
4.1 display "x is 0"
end
Multiple selection (if - else )
127

 2(b) Flow chart start

true

false
true
false true

false

end 127
Multiple selection (switch)
128

 Example :

If the letter grade is an A, Letter grade Message


then the program should A Excellent
display the message B Above average
“Excellent”, if the grade is a C Average
B, then display “Above D Below average
average” and so on. (refer
F Below average
the table)
Multiple selection (switch)
129

1. IPO Analysis:

Input: grade

Process: To identify the grade based on the value given

Output: “Excellent“ or “above average“ or “average” or


“below average“ or “error”
Multiple selection (switch)
130

 2(a) Pseudo code


start
1. read grade
2. grade value:
A display “excellent”
B display “above average”
C display “average”
D,F display “below average”
default display “error”
end
Multiple selection (switch)
131

start
 2(b) Flow chart
read grade

grade
A B C default
D, F

print Print “above print print Display


“excellent” average” “average” “below “error”
average”

end

131
Multiple selection (switch)
132

 2(a) Pseudo code start


1. read grade
2. if grade is A
2.1 display “excellent"
3. else if grade is B
3.1 display “above average"
4. else if grade is C
4.1 display “average“
5. else if grade is D
5.1 display “above average”
6. else
6.1 display “error
end
Multiple selection (switch)
Flow chart format:
start

true
expression1 statement1 break
false
true
expression2 statement2 break
false
* All statements can be true
input, processing or espression3 statement2 break
output
default

end
Nested if-else (switch)
134

start
 2(b) Flow chart
read grade
true
case grade A print “excellent”
false true
case grade B Print “above average”
false true
print “average”
case grade C
false true
case grade D,F print “below average”
false
Display “error” false

end 134
Try yourself
 Write IPO, pseudocode and draw a flowchart to enter a
number and if the number is 0, print “number is zero”.
 The program will receive 2 numbers as input. Calculate the
sum of the 2 numbers
 Write the IPO, pseudocode, and draw a flowchart if score
more than 40 and mark equal to 100 print Full Mark else print
OK.
Try yourself
 Write IPO, pseudocode and draw a flowchart to enter a
number and if the number is 0, print “number is zero”.
 The program will receive 2 numbers as input. Calculate the
sum of the 2 numbers
 Write the IPO, pseudocode, and draw a flowchart if score
more than 40 and mark equal to 100 print Full Mark else print
OK.
Try yourself
 Write IPO, pseudocode and draw a flowchart to enter a
number and if the number is 0, print “number is zero”.
 The program will receive 2 numbers as input. Calculate the
sum of the 2 numbers
 Write the IPO, pseudocode, and draw a flowchart if score
more than 40 and mark equal to 100 print Full Mark else print
OK.
Try yourself

 If x is greater than y, display “x is bigger than y” else


display “x is smaller than y”.
139

TOPIC: 8.2
PROBLEM SOLVING
8.2.3: Design a Solution
8.2.3.3 Control structure (Repetition)
Learning Outcome
140

 Explain the purpose of repetition control structure


 Apply appropriate control structure in problem
solving
 while
 for
 do while
What is repetition control structure?
141

 Repetition structure allows a sequence of instruction


to be executed repeatedly until a certain condition is
reached
 The looping structure has TWO forms:
 while
 for
 do while
The essentials of repetition
142

 The loop counter (loop control variable ):


 Counts the number of repetitions in the counter-controlled loop
 Controls the execution of loop

 The loop counter requires the following to be known in advance


1. Name of a loop counter
2. Initial value of the loop counter
3. Increment (or decrement) by which to modify the loop counter
in each traversal
4. Condition to test the final value of loop counter
Repetition: while Construct
143

 The while construct has the general form:


while (expression)
statement(s) block;
• where the expression is first evaluated.
• If it is true (not zero), the *statement(s) is executed,
• else if it false (zero), the statement is bypassed.
* note: statement(s); which can be a block of statements – more
than 1 statement
Applying Algorithm in while Construct
144

1. Pseudocode
start
initialize counter
while (expression)
statement(s)
counter increment
end
Applying Algorithm in while Construct
145

2(a) Flow Chart start

initialize counter

False while
(expression)
True
end statement(s)

counter increment
The Counter Table for while Construct
146

counter expression input process output counter


increment
initial value of condition to IPO analysis increment to
counter test modify the loop

Example of while counter table:


i i <= 3 input process output i=i+1
Example 1: while Construct
147

Problem Statement:
• Calculate the area of a rectangle for 3 times.
width
height

Remember to plan your algorithm.


• Do Problem Analysis.
• Transfer to Pseudocode or Flow Chart.
Example 1: while Construct
148

1. IPO Analysis:

Input:width, height
Process: area = width * height
Output: area
i i <= 3 width, height area = width * height area i=i+1

while counter table


Example 1: while Construct
149

1. IPO Analysis:
Input:width, height
Process: area = width * height
Output: area
i i <= 3 width, height area = width * height area i=i+1

1 T 2
2 T 3
3 T 4
4 F Loop terminate

while counter table


Example 1: while Construct
150

start 2(a) Pseudocode


1. initialize counter initial value of counter
i=1
2. while (i <= 3) condition to test
3. input width, height
4. calculate area of rectangle
area = width * height IPO analysis
5. print area
6. counter increment increment to
i=i+1 Repeat step 2modify
– 6 untilthe loop
7. repeat until i > 3 expression is false
end
Example 1: while Construct
151

2(b) Flow Chart start

i=1

False
(i <= 3)
True
end width, height

area = width * height

area i=i+1
Repetition: do while Construct

 The do-while loop is similar to the while loop in that


the loop continues as long as the specified loop
condition remains true.

 The main difference is that the condition is checked


at the end of the do-while statement.
Repetition: do while Construct

 The do-while structure test the loop continuation


condition after the loop body is performed.

 The loop body will be executed at least once.

 The statement will not be executed if the expression is


false.
Applying Algorithm in do while Construct
• do-while statement has a general form :
initialization
do
statement block;
increment;
while (expression1)
Applying Algorithm in do while Construct
start
2(b) Flow chart
Initial value

Statement

Increment

Expression TRUE

FALSE
end
Example 2: do while Construct
1. IPO analysis
Write the IPO, pseudocode and draw a flowchart to display
the numbers 1 to 3 on the screen
IPO
Input : none
Process : repeat process 3 times

Output : count
Example 2: do while Construct
2(a) Pseudocode
Pseudocode
initialize the count variable to 1
do
display the count
add 1 to the count

repeat while ( the count is less than


or equal to 3 )
end do-while
Example 2: do while Construct
start
2(b) Flow chart
Initialize the count variable to 1

Display count
TRUE
Add 1 to count

(count <= 3)
FALSE
end
Repetition: for Construct
159

 The for construct has the general form:


for (initialization; expression; incerement)
statement;
• where the initialization refers to the initial value of a loop counter.
• The expression determines whether the loop should be continued; if it is
true (not zero), the *statement(s) is executed, else if it false (zero), the
for Iloop is terminated.

* note: statement(s); which can be a block of statements – more than 1 statement


Applying Algorithm in for Construct
160

2(a) Pseudocode

start

for (initialize counter; expression; counter increment)


statement(s);
end
Applying Algorithm in for Construct
161

start
for (initialize counter; expression; counter increment)
statement(s);
end

• After one-time initialization, the expression is first evaluated.


• If it is false, the for loop is terminated; if it is true the statement(s) in the loop is
executed.
• And then the incrementation is performed.
• The expression condition is again evaluated, until the expression becomes false.
Applying Algorithm in for Construct
162

2(b) Flow Chart start

initialize counter

False
(expression)

True
end statement(s)

counter increment
The Counter Table for for Construct
163

counter expression input process output counter


increment
initial value of condition to increment to
counter test IPO analysis modify the loop

Example of for counter table:


i i <= 3 input process output i=i+1
Example 3: for Construct
164

Problem Statement:
• Calculate the area of a rectangle for 3 times.
width
height

Remember to plan your algorithm.


• Do Problem Analysis.
• Transfer to Pseudocode or Flow Chart.
Example 3: for Construct
165

1. IPO analysis:
Input: width, height
Process: area = width * height
Output: area
i i <= 3 width,height area = width * height area i=i+1

for counter table


Example 3: for Construct
166

1. IPO Analysis:
Input: width, height
Process: area = width * height
Output: area
i i <= 3 width,height area = width * height area i=i+1

1 T 2
2 T 3
3 T 4
4 F Loop terminate

for counter table


Example 3: for Construct
167

start 2(a) Pseudocode


initial value of counter
1. initialize counter
i=1
2. for (i <= 3) condition to test
3. read width, height
4. calculate area of rectangle IPO analysis
area = width * height
5. print area
6. counter increment increment to
modify the loop
i=i+1
7. repeat until i > 3 Repeat step 3 – 7 until
end expression is false
Example 3: for Construct
168

2(b) Flow Chart start

i=1

False (i <= 3)
True
end width, height

area = width * height

area i=i+1
Accumulating in Problem Solving
169

• Accumulating or summing is a task a program must often perform.


• Accumulating means summing a group of numbers:
1. where a variable is added to another variable,
2. which holds the value of the sum or total.

• The expression for accumulating is as follow:


2 1 2 1

sum = sum + num total = total + marks


Example 4: Accumulating in Sequence Structure
170

Problem Statement:
Calculate the average of three numbers.
Problem Analysis:
Accumulating
Input: num1, num2, num3
Process: total = num1 + num2 + num3
average = total / 3
or
average = (num1 + num2 + num3) / 3
Output: average
Example 5: Accumulating in looping Structure
171

Problem Statement:
• Calculate the average of three numbers.

Problem Analysis: Accumulating


Input: num
Process: total = total + num
average = total / 3
Output: average
Example 5: Accumulating in looping Structure
172

1. IPO analysis:
Input: num
Process: total = total + num
average = total / 3
Output: average
total i i <= num total = total + i=i+1 average = total / 3 average
3 num
0 1 T 70 70 2
2 T 80 150 3
3 T 90 240 4
4 F Loop terminate average = 240 / 3 80
Using accumulating in while construct (while counter table)
Example 5: Accumulating in while Construct
173

start
1. initialize total initial value of total
total = 0 2(a) Pseudocode
2. initialize counter initial value of counter
i=1
condition to test
3. while (i <= 3)
4. input num
5. accumulate total IPO analysis
total = total + num
6. counter increment increment to
i=i+1 modify the loop
7. repeat until i > 3 Repeat step 3 – 6 until
8. calculate average expression is false
average = total / 3
9. print average IPO analysis
end
Example 5: Accumulating in while Construct
174

2(b) Flow chart


start
total = 0
i=1
False
(i <= 3)
True
average = total / 3 num
average total = total + num
end i=i+1
Summary
175

What have you learned?


• The three forms of repetition control structure:
• while
• for
• The loop counter requirement.
• Apply repetition control structure in problem solving.
• Remember to plan your algorithm.
• Do Problem Analysis.
• Transfer to Pseudocode or Flow Chart.
• Applying accumulating in repetition.

Potrebbero piacerti anche