7problem Solving and Program Design
7problem Solving and Program Design
Problem
S
o
l
v
i
n
g
Ms D
B
r
0
2
a
o
n
w
d
n
e
P
1
r
o
g
r
a
E
m
D
e
This booklet contains notes related to Problem
Solving and Program Design. The notes
follow the CSEC syllabus for the 2021
Information Technology exam.
CSEC IT Class
June 2021 Sitting
1-869-661-2282
[email protected]
SPECIFIC OBJECTIVES
1. Outline the steps in problem solving
In problem solving, there are a series of steps that are required in order to
achieve a solution.
This is taking one large complex problem and strategically breaking it into
smaller simpler problems. The smaller simpler problems can be solved much
easier on their own. After these smaller tasks are solved, their solutions are
combined which would ultimately result in solving the large complex problem.
Example
If I take 10 cards, each with a letter and in random order, and turn them down
on a desk, would you be able to find letter "L" quickly?
However, if I take these same 10 cards, arrange them in ascending order and
turn them down on the desk, would this make it easier to find letter "L"?
What strategy would you utilize to find letter "L" after choosing the first card?
You may probably have said that after choosing the first letter, maybe card 4
which was "F", you would choose a higher card since the cards are arranged in
ascending order. And thereafter, you would choose a lower card if the letter was
after "L" and using this technique, you will gradually find letter "L".
By taking what may initially seem to be a difficult task and breaking it up into
smaller parts and using a variety of strategies, it becomes easier to find a
solution, in this case, the letter "L".
3. Define a problem by decomposing it into its significant components
Defining the problem involves a problem statement (a clear definition of the
problem that needs to be solved). The problem statement must then be broken
down into its main components
Inputs – the data you are provided with or have to obtain from the user.
Some words that help you identify the inputs are: read, input, enter,
given, accept.
Outputs – The results that should be produced. Some words that help
you identify the outputs are: print, calculate, output, display.
The word read tells us that the input will be in the form of two numbers. The
desired result is the total, so we’ll call the output total. Each task that must be
performed counts a processing. This means that reading the two numbers,
calculating their total and printing the total will all fall under processing
E.g., 2 Read the price of an item and its type. A 5% discount is to be given
on all books. If the item is a CD then there will be a 10% discount. All
other items are to get a 2% discount. Calculate and print both the discount
as well as the discounted price.
Input Processing Output
Item, type 1. Read the item and its type Discount
2. Calculate the discount Discounted price
3. Calculate the discounted price
4. Print the discount and discounted
price
Variable: an area of storage whose value can change during processing. For
example, name, age, area, month.
Constant: an area of storage whose value cannot change. For example, the
value of pi, the number of months in a year, the number of hours in a day.
Both variables and constants are given names in order to identify them. (these
are referred to as identifiers). It is a good practice to use names that refer to the
type of data that will be entered or stored. For example, age can be used to store
someone’s age and avg can be used to store average.
Data types – a particular kind of data item, as defined by the values it can take,
and the operations that can be performed on them.
Data types can be divided into three broad categories – textual, numerical and
Boolean
Textual data can include a combination of letters, symbols and numbers. This is
further divided into two categories:
Textual data contains things other than numbers, as a result of this, we don’t
perform calculations on textual data.
Numerical data – when it comes to programming, there are two main types of
numbers:
Integers – numbers that don’t have a decimal point. E.g., 1, -3, 200.
Real numbers (floating point) – Numbers with a decimal point. E.g., 6.8, 9.0,
0.56.
Boolean – data that must either be true or false. E.g. is x > 20, is y = 4.
Data Type
The grade a student got in a course character
e.g A, B, C, D, F
The time Usain Bolt takes to run a Real number (floating point)
100 m race
The number of books in a person’s Integer
bag
Whether or not a piece of luggage is Boolean
overweight
The cost of an item in a store Real number (floating point)
A person’s name string
Characteristics of an algorithm
It must have a finite number of steps. Algorithms should not go on
forever.
It should terminate and give the correct result. At the end of all
the required steps, the algorithm should come to an end and produce
the correct result.
Displaying Information
The output instruction
When a computer has finished processing data, the results are given in some
form of output. Output can be sent to the screen or the printer. Commands that
are used to produce the output are the words PRINT and DISPLAY and
OUTPUT
They can be used to display the value of a variable or to output the data that is
in a constant.
The command PRINT sum will print the value that was assigned to sum
Let us assume that A = 10. The command PRINT A will cause 10 to be printed
and not the letter A.
Variables used with the print instruction must not be new variables. They
should be variables that have been executed in an instruction prior to the
PRINT instruction.
H world
Created by Dianna Browne on March 12th 2022
START
PRINT “Hello world!”
STOP
Prompts
When entering data, messages may appear on the screen notifying the user of
what data is to be entered. These messages are called prompts or captions.
They begin with the word PRINT or DISPLAY, followed by the message
enclosed in quotation marks. Anything written inside the quotation marks
would be displayed as is by the computer.
In the above example, “Enter the name” will be displayed on the screen. This
will let the user know the data the program is expecting.
Anything enclosed in quotation marks while using the PRINT command will be
displayed on the screen. PRINT ‘name’ will display the word name.
There will be times when we wish to output a label or an explanation along with
a variable. This can be done with the use of string constants.
In the following example 20.00 is stored in the variable PRICE and ‘Price of an
item:’ is a constant
PRICE = 20.00
PRINT ‘Price of an item:’, PRICE
Performing Calculations
Processing data can involve performing calculations on the data given. These
calculations can be done by using arithmetic operators.
Arithmetic operator
Or
Solution
START
PRINT ‘Enter the length’
READ length
AREA = length * length
PRINT AREA
STOP
Write an algorithm to find the amount due given the cost and quantity of
an item
START
PRINT ‘Enter the cost and quantity’
READ cost, quantity
AmtDue = cost * quantity
PRINT ‘The amount due is’, AmtDue
Variables used in the formula for calculations must be variables that were used
in executed statements prior to the calculation instructions and not new
variables.
When you have to increase or decrease the value of a variable, the variable
appears on both sides of the assignment statement.
Example:
count = count + 1
num_left = num_left - 5
Selection statements
When a program is executed, each instruction is
processed in the sequence listed in the program,
unless specific instructions direct it to deviate and
select other instructions.
A condition is made up of three parts. The first part is a variable that was
carried out before. The second part is the relational operator, and the third part
is a variable that was carried out before or a constant.
C = 45 AND C < X
C = 45 OR C < X
Relational operators
These operators test or define some kind of relation between two entities. They
are important for making decisions. These operators take two operands,
compare their values and return their Boolean value (true or false). They are
mostly used in conditional expressions to test whether a condition is true or not.
Conditions can contain data of different data types. When the data of the
condition is the character data type, the data should be enclosed in quotation
marks.
e.g.
colour == “blue”
style == “straps”
heel == “4-inch”
grade <> ‘A’
Conditions are evaluated when the instruction containing it is carried out. When
the condition is met, the condition is said to be true; if the condition is not met,
then the condition is said to be false.
When using the command IF, the instructions forming the condition and
selection are called a construct.
The IF-THEN construct
IF <condition> THEN
<one or more instructions to be carried out if the condition is true>
ENDIF
IF marks the beginning and ENDIF the end of the construct. In this construct,
the instructions between IF and ENDIF are only executed if the condition is
true.
Read the time. If the time is 11, output Ring the bell
Solution
START
PRINT ‘Enter the time’
READ time
IF time = 11 THEN
PRINT ‘Ring the bell’
ENDIF
STOP
Solution
START
PRINT ‘Enter a number’
READ N
IF N > 100 THEN
N = N + 10
ENDIF
PRINT N
STOP
Syntax
IF <condition> THEN
< one or more instructions to be carried out if the condition is true>
ELSE
< one or more instructions to be carried out if the condition is false>
ENDIF
Input the age of a person. If the age is greater than 35, output ‘old person’
otherwise output ‘young person’.
Solution
START
PRINT ‘Enter the age’
Read age
IF age > 35 THEN
PRINT ‘old person’
ELSE
PRINT ‘young person’
ENDIF
STOP
A student is given a 5% discount off the fees for a course if the fees are paid
before 30 days. Read a fee and the number of days. Output the fee,
discount amount, and the fee less the discount amount.
START
PRINT ‘Enter the fee and the number of days’
READ fee, days
IF days < 30 THEN
discountamt = fee * 5/100
ELSE
discountamt = 0
ENDIF
amtdue = fee – discountamt
PRINT ‘Fee’, fee
PRINT ‘Discount amount’, discountamt
PRINT ‘Fee less discount amount’, amtdue
STOP
START
IF <condition> THEN
<one or more instructions>
ELSE
IF <condition> THEN
<one or more instructions>
ELSE
IF <condition> THEN
<one or more instructions>
ENDIF
ENDIF
ENDIF
STOP
This variant includes the ELSE IF clause which allows for the testing of a series
of conditions in a prescribed order. When the statement list corresponding to
the first true condition is found, the instructions are executed. All other
statements that a connected to conditions are skipped.
A stadium has 4 stands, A, B, C and D. The admission fee for stand A is
$2.00, stand B is $2.50, stand C is $4.00 and stand D is $5.00. Read a stand
and the number of spectators in the stand. Calculate and print the revenue
for the stand.
Solution
START
PRINT ‘enter a stand and the number of spectators’
READ stand, spectators
IF stand = ‘A’ THEN
revenue = spectators * 2.00
ELSE
IF stand = ‘B’ THEN
revenue = spectators * 2.50
ELSE
IF stand = ‘C’ THEN
revenue = spectators * 4.00
ELSE
IF stand = ‘D’ THEN
revenue = spectators * 5.00
ENDIF
ENDIF
ENDIF
ENDIF
PRINT ‘Stand’, stand
PRINT ‘Revenue’, revenue
STOP
Logical operators
These allow a program to make a decision based on multiple conditions. Each
operand is considered a condition that can be evaluated to a true or a false value.
The value of the conditions is used to determine the overall value of a
compound statement (placing two operands together and joining them with a
logical operator).
4+7=
C = 45 And C < X
Truth Tables
A truth table is a tabular representation of all the combinations of values for
inputs and their corresponding outputs. It is a mathematical table that shows all
possible outcomes that would occur from all possible scenarios that are
considered factual, hence the name. Truth tables are usually used for logic
problems as in Boolean algebra and electronic circuits.
The basic operations in truth tables:
In order for promotion from a lower stream to a higher stream, you have to have
a yearly average >=85 OR promotion exam average has to be >=80
P Q P OR
Q
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
This glass is full. (True) OR
This glass is empty. (True) will produce a truth value of true
Negation: A NOT operation is one that is the opposite of the original value.
P NOT P
TRUE FALSE
FALSE TRUE
C = 15, X = 20
C = 45 False
NOT (C=45)
How do we know the different amount of true and false to ensure that
all possible combinations are accounted for?
Start with the rightmost column for each statement and interchange
every true with a false for the powers of two starting from 20.
Every time we move one place to the left, increase the power of two
by one then interchange the true and false statements accordingly.
22 = 4 21 = 2 20 = 1
A B C A AND B AND C
TRUE TRUE TRUE
TRUE TRUE FALSE
TRUE FALS TRUE
E
TRUE FALS FALSE
E
FALSE TRUE TRUE
FALSE TRUE FALSE
FALSE FALS TRUE
E
FALSE FALS FALSE
E
Solution
START
PRINT ‘Enter the day’
READ day
IF day = ‘Monday’ OR day = ‘Tuesday’ THEN
PRINT ‘Correct day’
ENDIF
STOP
Case statements
A case statement is a control structure that allows a selection to be made
between several sets of statements. The choice is dependent on the value of
some expression.
START
PRINT ‘Enter the student’s mark’
READ mark
Case based on mark
mark >=100
Report “Perfect Score”
mark > 89
Report “Grade = A”
mark > 79
Report “Grade = B”
mark > 69
Report “Grade = C”
mark > 59
Report “Grade = D”
Default
Report “Grade = F”
End Case
PRINT ‘The student’s grade is’, Grade
STOP
Loops (iteration)
A loop is the repeating of instructions until a condition is met. Loops are
specifically useful when you have to perform the same task multiple times.
Types of loops
1. For loop
Syntax
FOR <variable> = <beginning> TO <ending> STEP <increment> DO
<instructions which are to be repeated>
ENDFOR
FOR is the beginning and ENDFOR the ending of the loop. The variable is
used to count the number of times the loop is executed. The value of this
variable starts at the beginning value and is increased by one each time the
loop is executed, unless otherwise directed by the STEP clause.
The STEP clause indicates how much the loop variable is to be increased by
each time the loop is executed. The STEP clause is not necessary if the
increment is 1. Use the minus sign (-) with the increment value to decrease
the loop variable value.
When the end value is reached, the loop terminates and the instruction
following ENDFOR is then executed.
The beginning, ending and increment values can be constants or variables.
Variables give greater flexibility for altering the number of times the loop is
required to repeat. When variables are used, the said variables must be read
as input or stored in the computer’s memory before the instruction is
encountered.
Write an algorithm to print the numbers from 1 to 10
Solution
START
FOR count = 1 To 10 DO
PRINT count
ENDFOR
STOP
Solution
START
FOR count = 10 TO STEP -2 DO
PRINT count
ENDFOR
STOP
Write an algorithm to calculate and print the average score for each
student in a class of 25. Each student was given three tests.
Solution
START
FOR count = 1 TO 25 DO
READ score1, score2, score3
sum = score1 + score2 + score3
average = sum/3
PRINT ‘The average is’, average
ENDFOR
STOP
Write an algorithm that reads N ages and for hose that are more than
65, say ‘Senior citizen’
Solution
START
PRINT ‘Enter the number of ages you are going to enter’
READ N
FOR count = 1 TO N DO
PRINT ‘Enter the age’
READ age
IF age > 65 THEN
PRINT ‘Senior citizen’
ENDIF
ENDFOR
STOP
2. WHILE LOOP
Syntax
<an initial value for the condition>
WHILE <condition> DO
<instructions which are to be repeated
ENDWHILE
The initial value for the condition can be stored in a variable which is read
or it can be a value which is assigned to a variable.
The initial value is necessary so that the comparison for the condition can be
made when the WHILE instruction is executed the first time.
The condition is made up of the said variable which stores the initial value
called the loop variable, an operator and a termination constant. The
termination constant is known as the dummy value or the sentinel value. A
dummy value is not a real value for the problem being solved. For example,
999 could be the dummy value for terminating the entry of ages of
individuals, as an age of 999 is not real. The variable chosen to form part of
the condition must match the data type of the dummy constant.
For example
WHILE A <> 999 DO (numeric constant)
WHILE A < 20 DO (numeric constant)
WHILE name <> “END” (string constant)
Write an algorithm to calculate and print the average of three (3) scores
for a number of students terminated by 999
START
PRINT ‘Enter the three grades. Enter 999 for the first grade to stop’
READ A, B, C
WHILE A <> 999 DO
SUM = A + B + C
AVERAGE = SUM/3
PRINT ‘The average is’, AVERAGE
PRINT ‘Enter the three grades. Enter 999 for the first grade to stop’
READ A, B, C
ENDWHILE
STOP
Write the algorithm and a program that finds the average for an
unknown set of positive numbers.
Start
Sum = 0
Count = 0
Using a while loop, write a program that accepts the name, price and
quantity of some items. Calculate the amount due for each item.
Output the name, price, quantity and amount due for each item.
Algorithm
Start
Print ‘Enter the name, price and quantity of the item, Enter END to stop’
Read name, price, quantity
While name <> ‘END’ do
Amount_due = price * quantity
Print ‘Name of item’, name
Print ‘price of item’, price
Print ‘quantity purchased’, quantity
Print ‘amount due’
Write an algorithm and a program that requests the first names and
ages of some people. Output and print their names and ages.
Start
Print ‘enter the name and age’
Read name, age
While name <> STOP do
Print ‘Name of individual’, name
Print ‘Age of individual’, age
Print ‘enter the name and age’
Read name, age
Endwhile
Stop
3. Repeat until
The REPEAT UNTIL loop is a loop that executes a block of statements until
a given condition evaluates to true. The condition will be re-evaluated at the
end of each iteration of the loop, allowing code inside the loop to affect the
condition in order to terminate it.
Syntax
REPEAT
<instructions to be repeated>
UNTIL <condition>
Sequence
Write an algorithm that reads the radius of a
circle. Calculate and print the area.
START
READ r
AREA = 3.14 * r * r
PRINT AREA
END
START
READ fare, age
IF age < 12 THEN
Rate = 0.0
ELSE IF age < 24 THEN
Rate = 0.70
ELSE
Rate = 1.0
ENDIF
ENDIF
PRINT fare * rate
STOP
For loop
Initialisation count = 1
FOR count = 1 TO 10 DO
automatically increase count by 1
While loop
Repeat Until
The trace table stimulates the flow of execution. Statements are executed step
by step and the values change when an assignment statement is executed.
When designing a trace table, draw a column for each variable used in the
algorithm and draw enough rows to form the cells to store the values.
Start tracing from the top of the algorithm and write the appropriate value in the
first vacant cell for the variable which is currently being assigned a value. A
variable can store only one item of data at a given time. The current value is the
value that should be entered in the vacant cell.
If the value of the variable is to be printed, write the value on your answer sheet
as soon as the value is obtained rather than on completion of the entire table.
When printing is required within a loop, several values may have to be printed
for the same variable depending on the number of times the print instruction
was carried out. If printing is required only outside a loop, all of the values
within the loop for the variable to be printed may not have to be printed.
1 START
2 READ r
3 AREA = 3.14 * r * r
4 PRINT AREA
5 STOP
C=0
READ QTY, PRICE
WHILE QTY <> 0 DO
TOTAL = QTY * PRICE
C = C + TOTAL
READ QTY, PRICE
ENDWHILE
S P T Q TOT
0
4 1 2 4 2
2 6 12 8
3 4 14 12
4 1 16 13
5