Outline The Steps In Problem Solving
When you are faced with a problem, which of the following would you do?
1.Quit?
2.Yell for ‘Mummy’?
3.Migrate?
4.Pout?
5.Try to find a solution?
STEPS TO PROBLEM SOLVING
1. Define the problem
2. Find a solution to the problem
3. Evaluate alternative solutions
4. Represent the most efficient solution as an algorithm (a series of steps to solve the
problem)
5. Test the algorithm with sample data (dry run)
6. Fix errors or debug the algorithm
7. Code the algorithm using a programming language to create a computer
program
THE DIVIDE AND CONQUER APPROACH
The idea here is to repeatedly split a large problem into a number of smaller sub-problems
until a complete solution is identified.
Let us use an everyday example using the divide and conquer method, such as assembling
peanut butter sandwich. Take a look at the following video: https://youtu.be/RmbFJq2jADY
Lets use another example: Given a loaf of bread, you need to divide it into 8 pieces without
using a ruler or tape measure.
Fig: Slicing a bread into 1/8th1/8th pieces.
How would you go about cutting this loaf of bread?
Step 1 - First divide the bread into half, to get 2 pieces.
Step 2 - Cut these pieces into 2 each to get 4 pieces.
Step 3 - Repeat the process until you have 8 pieces
Decomposing a Problem Into Its Significant
Parts CREATING AN IPO CHART
A useful tool for decomposing a problem into its significant parts is the IPO (Input,
Processing, Output) Chart, which is sometimes known as a Defining Diagram. An IPO
Chart is a table with three columns labeled to represent the components.
This involves decomposing the problem into three key components:
1. Input: the data that is required
2. Output: the expected results
3. Processing: the tasks/actions that must be performed to convert input into output
CONTROL STRUCTURES
The statements in the processing component is governed by control structures. A
control structure determines the order in which statements are processed or
executed. There are 3 types:
1. Sequential Structure - this refers to line-by-line execution of statements in the
order in which they appear
2. Selection Structure - tests a condition and carries out the appropriate set of
instructions depending on whether the condition is either True or False 3. Repetition
(Loops) - repeating a list of statements until a condition is satisfied. This can be done
either a fixed number of times or an unknown number of times.
KEYWORDS
Input can be identified by the keywords : READ, ACCEPT, GET, INPUT Outputs can
be identified by the keywords: PRINT, DISPLAY, RETURN, OUTPUT Assigning of
values can be identified by the keyword: SET
PROBLEM 1:
Write a solution to read three numbers and calculate and print the total.
INPUT PROCESSING OUTPUT
3 numbers 1. Get 3 numbers Total
e.g. num1, 2. Add numbers together
3. Print total.
num2, num3
PROBLEM 2:
Given three integers representing the age of three boys respectively, write a solution to find
their average age.
INPUT PROCESSING OUTPUT
3 integers 1. Read/accept/get 3 integers Average
e.g.age1, age2, age3 2. Add the 3 ages
3. Divide total by 3
4. Print the average,
Variable, Constant and Data Types
VARIABLES
* In the computer, values are stored in memory locations.
* There are many memory locations. In order to keep track of where our values are stored, we
need to place a label or identifier in a
particular memory location.
* The label or identifier is called a variable.
* A variable is a symbolic name assigned to a memory location that stores a particular value. It
is good practice to choose variable names that reflect the kind of data that is being stored, e.g.
num1, age1, sum, average etc.
INITALIZATION OF VARIABLES
* Variables that are used as counters or used to store totals should always be assigned an
initial value of zero (0) before they are used.
* This is called initialization, e.g. Count = 0
* This ensures that the variable is cleared of any values that may have been assigned in a
previous execution of the program
CONSTANT
This is a variable whose value is fixed, i.e. the value does not change, e.g tax = 0.15
DATA TYPES
Each piece of data stored in memory is of a specific data type. In programming there are five (5)
basic data types.
Data Type Description Example
Integer Whole numbers - can be 24, -90, 86
positive or negative
Real Numbers with decimal places -2.6, 3.142, 45.876
Character A letter, digit or special character A, 5, m, @
String A group of characters "Hello World", "FindSum", "Tax2"
Boolean The result of testing a condition True or False/Yes or No
Sequential Structure and Operators
SEQUENTIAL STRUCTURE
A sequential structure shows a process, a series of steps or an order of events. In problem
solving, sequential structure includes:
1. Input statements: these accept data entered into the computer and store the value in the
location with the given variable name e.g.
input name
get num1, num2
read price
2. Output statements: these display/output data that is in the computer’s memory e.g.
Output Sum
Print total_cost
Display “ Enter student’s name”
3. Assignment statements: gives the value on the right of the assignment operator (equal
sign) to the variable on the left of the assignment operator. This can be considered as "hard
coding" the data, e.g.
N= 100
Count = 0
Answer = “END”
4. Calculation (Processing) statements: uses the values on the right of the assignment
operator and performs mathematical operations, then assigns the result of the calculation to the
variable on the left of assignment operator e.g.
Sum = num1 + num2
New_Price = Old_Price - Discount
Average = Total/5
OPERATORS
Operators can be either Mathematical (computes arithmetic expressions) or
Logical (performs decision making where the answer is either True or False).
The Mathematical operators are:
Symbol Description Example
+ Addition 2+1
- Subtraction 6 -2
/ Divide By 54/2
* Multiplication 4*9
^ Raised to the power to 4^2
DIV Integer Division 17 DIV 5 = 3
MOD Remainder 17 MOD 5 = 2
The Logical operators are:
Symbol Description Example
= Equal to x = 35
> Greater than 8>5
< Less than 3<9
>= Greater than or equal to x>=8
<= Less than or equal to x<=60
<> Not equal to 40 <>34
The logical operators compare Boolean expressions (an expression that results in a value of
either TRUE or FALSE) and returns a Boolean result (either TRUE or FALSE). These include:
1. AND
performs logical conjunction on two Boolean expressions. If both expressions evaluate to
True, then the And operator returns True. If either or both expressions evaluate to False, then
And returns False.
AND
Expression A Expression B Result
False False False
False True False
True False False
True True True
2. OR
Performs logical disjunction on two Boolean expressions. If either expression evaluates to
True, Or returns True. If neither expression evaluates to True, Or returns False.
OR
Expression A Expression B Result
False False False
False True True
True False True
True True True
3. NOT
Yields the opposite of the expression it evaluates. If the expression evaluates to
True, Not yields False; if the expression evaluates to False, Not yields True
NOT
Expression Result
False True
True False
Introduction To Algorithms
WHAT IS AN ALGORITHM?
An algorithm is a set of instructions written in a logical sequence that produces a solution to a
problem.
It is really used to expand the ‘processing’ part of the Defining Diagram in pseudocode or
pseudo-English.
Pseudocode is a language consisting of English-like statements used to define an algorithm.
ALGORITHMIC STRUCTURE
Header : Algorithm’s name or title
Declaration : Brief description of algorithm and variables used. i.e. A statement of
purpose as well as the initialization of variables
Body : Sequence of steps
Terminator : An end statement
ALGORITHM EXAMPLE 1
Write an algorithm that prompts the user to enter his/her name and prints a welcome message to
the user.
Solution:
Algorithm Welcome {Header}
This algorithm prints a welcome message for the user and displays his/her name. {Declaration} name
– stores the name which the user inputs {Variable}
Start
Print ‘Please enter your name’ Body Input name
Print ‘Welcome to the world of problem-solving’,name
Stop {Terminator}
ALGORITHM EXAMPLE 2
Construct an algorithm to prompt the user to input three (3) numbers and calculate the
average. The algorithm should printboth the sum and average.
Solution
Algorithm FindAverage {Header}
This algorithm calculates and prints the sum and average of three numbers. {Declaration}
num1,num2,num3 – stores the 3 numbers
Sum – stores the sum of the 3 numbers Variable(s) Average – stores the average of the 3
numbers Declaration
Start
Print ‘Enter three numbers’
Input num1, num2, num3
Set Sum to num1+num2+num3 Body Set Average to Sum/3
Print ‘The sum is: ‘,Sum
Print ‘The average is: ‘, Average
Stop {Terminator}
Flowcharts vs Pseudocode
FLOWCHARTS vs PSEUDOCODE
A Flowchart is a diagrammatic representation of an algorithm. It is usually used to
represent the ‘Body’ portion of an algorithm
* Pseudocode is more concise, closely resembles programming language * Flowcharts
gives a good view of the structure and flow of the logic in an program * Longer, more
complex solutions are better represented using pseudocode * Flowcharts must use
special geometrical objects that designate the basic steps of a program:
PSEUDOCODE & FLOWCHART
Start
Print ‘Enter three numbers’
Input num1, num2, num3
Set Sum to num1+num2+num3
Set Average to Sum/3
Print ‘The sum is: ‘,Sum
Print ‘The average is: ‘, Average
Stop
Selection Structure IF THEN ELSE
SELECTION STRUCTURES
Selection (decision)- This construct is used when no action needs to be performed if the
expression returns false.
The IF…THEN selection statement
Syntax:
IF (expression) THEN
{Statement (s)} Execute statement(s) if logical expression is TRUE
Eg.1) Write an algorithm to read the score of a student in an examination and determine
whether the student has passed. If the score is greater than or equal to 50, the student has
passed. Print whether the student has passed.
Answer
Start
Print (‘Please enter the score’)
Input Score
IF Score >= 50 THEN
Print ‘PASS’
Stop
The IF … THEN … ELSE construct syntax:
IF (expression) THEN
{Statements} executed only if condition is TRUE
ELSE
{Statements} executed only if condition is FALSE
ENDIF
Only one group of statements could be executed each time the program is executed
Eg.2) Using the scenario in Example1, determine whether the student has passed or failed
and print the result.
Answer
Start
Print (‘Please enter the score’)
Input Score
IF Score >= 50 THEN
Print ‘PASS’
ELSE
Print ‘FAIL’
ENDIF
Stop
Eg.3) Write an algorithm which accepts a number and determines whether the number is
‘odd’ or ‘even’. Print the result.
Answer
Start
Print(‘Please enter a number’)
Input num
IF (num MOD 2 = 0) THEN
Print(num,’ is even’)
ELSE
Print(num,’ is odd’)
ENDIF
Stop
THE NESTED IF construct syntax
IF (expression 1) THEN
{Statements} executed only if condition in expression 1 is TRUE
ELSE IF (expression 2) THEN
{Statements} executed only if condition in expression 2 is TRUE ELSE
{Statements} executed only if condition in expression 2 is FALSE ENDIF
ENDIF
Eg.4) Write an algorithm which reads the age of a person and determine whether he/she is a
student. The person is considered a student if he/she is between the ages of 5 and 18. If the
person is under the age of 5 then he/she is a ‘toddler’. Otherwise, the person is an adult. Print
the age of the person.
Answer
Start
Print(‘Please enter the person’s age’)
Input age
IF (age <= 18) AND (age >=5) THEN
Print(‘You are a student’)
ELSE IF (age < 5) THEN
Print(‘You are a toddler’)
ELSE
Print(‘You are an adult’)
ENDIF
ENDIF
Stop
Repetition Structures FOR Loop
‘FOR’ LOOP CONSTRUCT
The FOR loop is a repetition control structure that allows you to execute either a single
statement or set of statements a specific number of times.
The FOR loop construct syntax:
FOR <counter> = <start value> TO <end value> DO
{Statements}
ENDFOR
e.g. FOR X = 1 to 10 DO
{Statements to be executed}
ENDFOR
NOTE: The FOR loop is used when the required number of iterations (repetitions) is
known beforehand.
Some other simple examples include:
FOR x = 1 to 100 DO
FOR weekday = 1 to 5 DO
Print (‘I must not sleep in class’)
Print(‘Go to school’)
ENDFOR
ENDFOR
FOR age= 13 to 19 DO FOR x = 1 to 12 DO
Print(‘You are a teenager’) y=x*2
ENDFOR Print(x,’ times 2 = ‘,y)
ENDFOR
FOR num = 1 to 20 DO Saturday = 2
Print(‘The number is: ‘,num) Sunday = 3
ENDFOR FOR day = Saturday to Sunday
DO Print(‘It is the weekend’)
ENDFOR
Eg.) A man works 40 hours per week and he is paid an hourly rate of $50.00 per hour.
Construct pseudocode algorithm and flowchart to read the names and hours worked for 10
employees.
Determine and print their weekly wages along with their names.
Answer
Start
FOR x = 1 to 10 DO
Print (‘Please enter a name and hours worked’)
Input Name, Hours
Set Wage to Hours * 50
Print (Name,’ $’,Wage)
ENDFOR
Stop
Eg 2.) Write a pseudocode algorithm to print a conversion table to convert miles to
kilometres. The table ranges from 5 to 100 miles in steps of 5 [1 mile = 1.161km].
Answer
Start
FOR x = 1 to 100 DO STEP 5
km = x * 1.161
Print(x,’ miles = ‘,km)
ENDFOR
Stop
WHILE loop vs REPEAT UNTIL
COMPARISON OF ‘WHILE’ LOOP AND ‘REPEAT...UNTIL’ LOOP
‘WHILE’ LOOP CONSTRUCT vs ‘REPEAT…UNTIL’ LOOP CONSTRUCT
SIMPLE EXAMPLES OF ‘WHILE’ vs ‘REPEAT...
Eg.) Write an algorithm to accept an unspecified amount of integers.Calculate and print the
sum of the numbers entered. The program should be terminated when the number 999 is
entered.
Answer: ‘WHILE’ LOOP
Answer: ‘REPEAT...UNTIL’ LOOP
Start
Start
Print(‘Please enter a number’)
Print(‘Please enter a number’)
Read(num)
Read(num)
WHILE (num <> 999) DO
REPEAT
sum = sum + num
sum = sum + num
Print(‘Please enter a number’)
Print(‘Please enter a number’)
Read (num)
Read(num)
ENDWHILE
UNTIL (num = 999)
Print(‘The sum is: ‘, sum)
Print(‘The sum is: ‘, sum)
Stop
Stop