Download as pdf or txt
Download as pdf or txt
You are on page 1of 186

Paper-II

“Practical Problem-solving and Programming”

Compiled by:
Farhan Rahmat
Index

Computer Science 2210

S.No Title Topic Page#

Top-down/modular design approach:


Practical problem solving – Practical problem solving – structure diagrams,

- Structure Diagram
- Algorithm
- Flowchart
o Common flow chart symbols
algorithms and flowcharts

o Use of variable names


o Mapping of values
o Use of conventional arithmetic
Unit -6 operator
o Apply suitable test data
o Validate and verify input data
o Dry running of flowcharts to
determine its function and outputs
o Writing flowcharts to solve
problems

Past paper questions

Introduction to pseudocode
- Command/Statement for use and
declaration of:
o Variable and constant
pseudocode

o Basic data types


Unit-7 o Single dimensional Array
- Commands/Statements for
o INPUT/OUTPUT
o Totaling and counting
o Iteration and selection
Past paper questions
Introduction to programming languages
- History of computer programming
- Types of programming languages
o Low level languages
o High level languages
- Translation of computer programs

Programming Concepts
o Role of Assemblers
o Role of Compiler
o Role of Interpreter
Unit-8 - Structure of a computer programs
o Data types and their declaration
o Iteration, selection, counting and
totaling
o Use of predefined procedures and
functions
- Arrays
o Declaration of array
o Index of array
o Reading values into array
Past paper questions
Introduction to databases
- Ranges of databases
- Data types
- Record structure
Databases

Unit-9 o Types of fields


o Length of field
o Record sizeS
o Coding and validation
o Key fields (Primary key)
o Perform a query
Past paper questions
Unit-6:
Practical problem solving – structure
diagrams, algorithms and flowcharts
Notes for O Level Computer Science 2210 By Farhan Rahmat

Advantages of designing a solution to a problem by splitting it up into smaller problems


(top-down/modular design)

Produce and describe top-down/modular designs using appropriate techniques, including


structure diagrams, showing stepwise refinement

Top down/modular design

Top-down design is when a problem is split into smaller sub-problems, which themselves are
split into even smaller sub-problems until each is just one element of the final program.

Benefits and drawbacks of modular programs

Structure diagrams

A structure diagram is a pictorial representation of a modular system.

Stepwise refinement

Stepwise refinement is the process of developing a modular design by splitting a problem


into smaller sub-tasks, which themselves are repeatedly split into even smaller sub-tasks until
each is just one element of the final program.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 2|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat

2.1 (e) produce algorithms to solve problems using both a program flowchart and
pseudocode

2.1 (f) understand algorithms presented in the form of program flowcharts and
pseudocode

Algorithm

An algorithm is a sequence of steps, which perform a specific task. In computing,


algorithms are usually represented as a program flowchart, or in pseudo-code.

Program flowchart

A program flowchart is a pictorial representation of an algorithm. Program flowcharts use


special symbols:

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 3|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat

Flowchart to output the first five square numbers:

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 4|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat

Pseudo-code

Pseudo-code is a simplified form of programming code that uses common programming


keywords, but does not use the strict syntax rules of a programming language.

An example of a pseudo-code algorithm:

BEGIN

INPUT CardNumber

REPEAT

INPUT PIN

IF PIN is wrong for this CardNumber THEN

OUTPUT “Wrong Pin”

END IF

UNTIL Pin is correct

INPUT Amount

IF there are enough funds THEN

Dispense Cash

Update customer‟s balance

ELSE

OUTPUT “Sorry, insufficient funds”

END IF

END

Algorithms should be evaluated using the following criteria:

• Efficiency
• Correctness
• Appropriateness

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 5|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat

Efficiency

An algorithm‟s efficiency can be judged in terms of:

• speed – how quick the algorithm produces the required output;


• memory requirements –how many lines of code the algorithm contains.

Correctness

Although an algorithm is expected to produce the correct outputs, correctness can still be
measured

in terms of:

• accuracy – how many decimal places Produce output with greater accuracy – e.g.
more decimal places;
• range – will the algorithm work with the complete range of inputs, or can it only deal
with positive numbers, whole numbers, numbers below 1 million, etc.
• reliability – will the algorithm always produce correct output within the range that it is
designed to work, or are there values which it will not accept (zero, for example).

Appropriateness

Appropriateness can be measured in terms of:

• length – if the problem is simple then a short algorithm would normally be expected;
• speed – if the output needs to be generated quickly, then the algorithm must be
able to complete quickly;
• memory requirements – an algorithm controlling a washing machine must not have
the need for a lot of memory!

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 6|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat

Flow Charts

Introduction
This section covers the use of flow diagrams (charts) in the production of algorithms.
Systems flowcharts are different and these are covered in a different section (Systems
analysis).

This section primarily covers four areas:

1. Common flow chart symbols


2. Writing flowcharts to solve problems
3. Dry running of flowcharts to determine its function and outputs
4. Exercises to test the above concepts
5. Topical past paper questions

1. Common flowchart symbols

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 7|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat

Understand and use assignment statements

Assignment
An assignment is an instruction in a program that places a value into a specified variable.
Some typical assignments are:

TheLength 20.5
TheUsersName$ “Charlie”
TheAreaTheWidth * TheLength
TotalCostLabelledCost + 15
Counter  Counter + 1

Note that the last example is a common method used to increment the value of a
variable. It could be read as:

“The new value of Counter is its existing value plus one”

Arithmetic operators including operators for integer

Addition, subtraction and multiplication

Powers

Division
A result of a division such as 17 ÷ 4 can be expressed either as a real (4.25) or as two
integers(4 remainder 1).

The integer method, in most programming languages, uses the operators DIV and MOD.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 8|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat

Relational operators, eg. =, <, <=, >, >= and <>

Relational operators are used in the format: [Expression] [Operator] [Expression] and will
always return a Boolean (True or False) value.

Relational operators are typically used with the IF selection and also within conditional
loops
(REPEAT-UNTIL or WHILE-WEND).

In the following table, the variables a and name$ have the following assignments:

a3+5
name$ “JAMES”

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 9|Page
Notes for O Level Computer Science 2210 By Farhan Rahmat

Boolean operators AND, OR and NOT

AND and OR
The AND and OR operators always return a Boolean result and are used in the format:

[Boolean] [Operator] [Boolean]

The following „truth‟ table summarises the result of the Boolean operations:

Values Results

NOT
The NOT operator reverses the result of the Boolean expression and is used in the format:

NOT [Boolean]

The following truth table summarises the NOT operation:

Examples of Boolean „logic‟


Consider the following algorithm, which is used to monitor a printer and display its output
via an
LCD display in the front panel:

IF NOT(PaperTrayEmpty) AND (FilesWaiting> 0) THEN


OUTPUT “PRINTING…”
ELSE
OUTPUT “PLEASE ADD PAPER”
END IF

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 10 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Validation

Presence check
Code can be added to check that a particular control has not been left empty or un-
checked:

Is
No Yes You have not
Username = “”
entered a
?
Username”)

Range check
Code can be added to check that a particular control has a value between an allowed
maximum and minimum:

The age that


Is
No Yes you have
(Age)< 11 OR (Age)
entered is not
> 70
within the
?
permitted range

Length check
Code can be added to check that a particular control has a value between an allowed
maximum and minimum:

The password
Is
No Yes that you have
Len(Password)> 12
entered is too
?
long

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 11 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

2. Writing flowcharts to solve problems


The following five problems are also covered in section 3.2 where the algorithms are
constructed using pseudocode. Candidates may choose to answer questions using either
flowcharts or pseudocode but a working knowledge of both techniques is well advised.

2.1 Example 1
A town contains 5000 houses. Each house owner must pay tax based on the value of the
house. Houses over $200 000 pay 2% of their value in tax, houses over $100 000 pay 1.5% of
their value in tax and houses over $50 000 pay 1% of their value in tax. All others pay no tax.
Write an algorithm to solve this problem in the form of a flowchart.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 12 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

2.2 Example 2
The following formula is used to calculate n: n = (x * x)/(1 – x). The value x = 0 is used to stop
the algorithm. The calculation is repeated using values of x until the value x = 0 is input.
There is also a need to check for error conditions. The values of n and x should be output.
Write an algorithm to show this repeated calculation in the form of a flowchart.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 13 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

2.3 Example 3
Write an algorithm in the form of a flowchart which takes temperatures input over a 100
day period (once per day) and outputs the number of days when the temperature was
below 20C and the number of days when the temperature was 20C and above.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 14 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

2.4 Example 4
Write an algorithm in the form of a flowchart which:

• inputs the top speeds (in km/hr) of 5000 cars


• outputs the fastest speed and the slowest speed
• outputs the average (mean) speed of all the 5000 cars

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 15 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

2.5 Example 5
A shop sells books, maps and magazines. Each item is identified by a unique 4 – digit code.
All books have a code starting with 1, all maps have a code starting with 2 and all
magazines have a code starting with 3. The code 9999 is used to end the algorithm.

Write an algorithm in the form of a flowchart which inputs the codes for all items in stock
and outputs the number of books, number of maps and the number of magazines in stock.
Include any validation checks needed.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 16 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

3. Dry running of flowcharts


Dry running of flowcharts is basically a technique to:

• determine the output for a known set of data to check it carries out the task
correctly
• check on the logic of the algorithm
• determine the function of the algorithm
• When dry running a flowchart it is advisable to draw up a trace table showing how
variables change their values at each stage in the algorithm. The advantages of
doing this are:
• if you make a mistake, it is easier to back track to where the error occurred rather
than starting from the beginning again
• there is less chance of an error being made
• encourages a more logical approach

The following three examples show all stages in the dry running for the given set of input
data:

3.1 Example 1
This algorithm inputs 3 numbers, each number goes through successive division by 10 until its
value is less than 1. An output is produced which contains the number input and a value
generated by the flowchart processing.

Data to be used: X = 85, 3190, -40

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 17 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

3.2 Example 2
This algorithm inputs 5 values and outputs how many input numbers were negative and
how many were positive.

Data to be used: N = 1, -5, 2, -8, -7

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 18 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

3.3 Example 3
This algorithm inputs the number of hours of sunshine recorded each day for a week (7
days). The output is the highest value for hours of sunshine and the average (mean) value
for the numbers of hours of sunshine per day.

Data to be used: hours = 9.0, 7.8, 1.2, 4.5, 10.0, 6.4, 3.1

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 19 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Questions:
Questions 1 to 7 are problems which require an algorithm to be written in the form of a
flowchart. Questions 8 to 10 require a trace table to be written and find the expected
output for the given set of data. The answers to these questions can be found in booklet 6.

1. Regis lives in Brazil and often travels to USA, Europe and Japan. He wants to be able to
convert Brazilian Reais into US dollars, European euros and Japanese yen. The
conversion formula is:

currency value = number of Reais X conversion rate

For example, if Regis is going to USA and wants to take 1000 Reais (and the exchange
rate is 0.48) then he would input USA, 1000 and 0.48 and the output would be: 480 US
dollars.
Write an algorithm, using a flowchart, which inputs the country he is visiting, the
exchange rate and the amount in Brazilian Reais he is taking. The output will be value in
foreign currency and the name of the currency.

2. As part of an experiment, a school measured the heights (in metres) of all its 500
students.

Write an algorithm, using a flowchart, which inputs the heights of all 500 students and
outputs the height of the tallest person and the shortest person in the school.

3. A geography class decide to measure daily temperatures and hours of sunshine per
day over a 12 month period (365 days)

Write an algorithm, using a flowchart, which inputs the temperatures and hours of
sunshine for all 365 days, and finally outputs the average (mean) temperature for the
year and the average (mean) number of hours per day over the year.

4. A small shop sells 280 different items. Each item is identified by a 3 – digit code. All items
that start with a zero (0) are cards, all items that start with a one (1) are sweets, all items
that start with a two (2) are stationery and all items that start with a three (3) are toys.

Write an algorithm, using a flowchart, which inputs the 3 – digit code for all 280 items
and outputs the number of cards, sweets, stationery and toys.

5. A company are carrying out a survey by observing traffic at a road junction. Each time
a car, bus or lorry passed by the road junction it was noted down.
10 000 vehicles were counted during the survey.
Write an algorithm, using an algorithm, which:
inputs all 10000 responses outputs the number of cars, buses and lorries that passed by
the junction during the survey outputs the number of vehicles that weren‟t cars, buses or
lorries during the survey.

6. Speed cameras read the time a vehicle passes a point (A) on the road and then
reads the time it passes a second point (B) on the same road (points A and B are
100 metres apart). The speed of the vehicle is calculated using:

The maximum allowed speed is 100 kilometres per hour. 500 vehicles were
monitored using these cameras over a 1 hour period.
Write an algorithm, using a flowchart, which:

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 20 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

• inputs the start time and end time for the 500 vehicles that were monitored
• calculate the speed for each vehicle using the formula above
• outputs the speed for each vehicle and also a message if the speed
exceeded 100 km/hour
• output the highest speed of all the 500 vehicles monitored

7. There are ten stations on a railway line:


1 ------ 2 ------ 3 ------ 4 ------ 5 ------ 6 ------ 7 ------ 8 ------ 9 ------ 10
The train travels in both directions (i.e. from 1 to 10 and then from 10 to 1). The fare
between each station is $2.
A passenger inputs the number of the station at the start of his journey and the
number of the destination station and the fare is calculated (e.g if a passenger gets
on a station 3 and his destination is station 9 his fare will be $12). The calculation must
take into account the direction of the train (e.g. a passenger getting on at station 7
and getting off at station 1 will also pay $12 and not a negative value!!).
A discount of 10% is given if 3 or more passengers are travelling together.
Write an algorithm, using a flowchart, which:
• inputs the number of passengers travelling
• inputs the station number of the starting point and the station number of the
destination
• calculates the total fare taking into account the direction of travel
• calculates any discount due
• outputs the cost of the tickets and prints the tickets

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 21 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

8. Draw the trace table and determine the output from the following flowchart using
the following data:

number = 45, -2, 20.5

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 22 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

9. Draw the trace table and determine the output from the following flowchart using
the following data (NOTE: input of the word “end” stops the program and outputs
results of the survey):

vehicle = car, car, lorry, bus, van, van, car, car, bus, car, end

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 23 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

10. Draw the trace table and determine the output from the following flowchart using
the following data:

X = 5, -3, 0, -3, 7, 0, 6, -11, -7, 12

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 24 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Past Papers Questions:


Modular Design/Top-down design:
(Computing 9691 Questions)

May/June 2006 (9691)


5. (a) Programs can be designed in modular form.
Discuss the advantages and disadvantages of designing programs in modular form.
[5]

(b) A program is to be written which will update the records in a sequential file
and then produce a backup copy.

Describe, using a diagram, the way that this problem can be split into modules to
prepare it for coding. [5]

May/June 2006 (7010)


1 Explain, using examples where appropriate, the meaning of these computer terms.
(e) top-down design

Oct/NOV 2006 (7010)


14 Give three benefits of using top-down design to write computer programs. [3]

May/June 2008 (9691)


1 Explain, using examples where appropriate, the meaning of these computer terms.
(c) top down design [2]

Oct/NOV 2008 (7010)


2 Describe two benefits of using top down design to develop computer software. [2]

May/June 2009 (9691)


A company specialises in creating websites for customers.
8. (a) As part of the process of designing a site, the company will use diagrams in
order to make understanding easier.
Describe two types of diagram that may be used by the company. [4]

May/June 2011. P23 (9691)

1. (a) Draw a suitable layout for the screen. [5]


3. Kris has written a program that will work out the wages for her staff. The main steps
foreach employee are: to work out the hours worked, work out the total earnings,
work out taxand finally print out how much will be taken home.

(a) Complete the structure diagram to show the modules that will be needed.

[3]

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 25 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

(b) The printout will be different for those staff who receive
cash and those who have theirearnings paid directly to a
bank account. Add the next level to the print module.

Oct/NOV 2011 P23 (9691)


1 Nathan is designing a software solution for stock control in a computer shop. He has
acolleague, called Andre, who will help him write the program. Nathan decides
tomodularise the solution.
(a) State why modularisation is a good idea. [1]
(b) As the first step in his design he splits the solution into the following main areas:
Initialisation, StockOrdering, Sales, SalesReport.
Complete the following structure diagram.

[1]
(c) SalesReport is made up of two modules, MonthlySalesReport and
AnnualSalesReport.
Add them to the structure diagram in (b). [2]

Oct/NOV 2012 P13 (7010)

2 New software is often developed using top-down (modular) design.


Give three benefits of using this method of development. [3]

Oct/NOV 2012 P21

1 Soni works for a software house which has been asked to design software for a cycle
hirecompany, Super Bikes.
Soni decides on the main tasks:
• collecting the information about new bikes
• entering details of repairs
• entering details of hirer
• entering details of payment
(a) Complete the structure diagram showing these tasks.

[2]
(b) The collection of information about repairs has three subtasks:
• input the repair needed
• input the parts list
• input the cost of the repair
Add these to the structure diagram in part (a). [1]
(c) State two reasons for dividing the main task into smaller tasks. [2]

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 26 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Flow Charts:

May/June 2006
9

Trace the flow chart using the numbers 2 and 3. Write down each of the values of N in the
orderthat they are printed out.
(a) 2 [1]
(b) 3 [2]

14 (b)
(b) Select words from the list below to complete the systems flowchart for electricity
billpayments.

errors master file sorted transaction file


update validate validated transaction file

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 27 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2006
17 The following flowchart shows how the bar code written on an item is used to find the
price,do stock control and produce an itemised bill. Select statements from the list below
tocomplete the flowchart.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 28 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2007

2 Describe, with examples, two types of test data which could be used to test a system. [4]

11 Study the following flowchart very carefully.

(a) Complete the following table showing the expected output from the flowchart for
thethree sets of input data:

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 29 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2007
11Majid lives in Cairo but often travels to Tokyo, Mumbai and Washington. A flow chart
hasbeen written so he can work out the local time in these three places.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 30 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 31 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2008
9 The following flowchart inputs two numbers, carries out a calculation and then outputs
theresult.

(a)Complete the following table for the three sets of input data.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 32 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2008
17 The following flowchart shows how sensors (which can be analogue or digital) and a
computer are used to control the temperature of a greenhouse for plants. Complete the
flowchart using the items from the list below.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 33 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2009
14 Study the flowchart very carefully.

(a) Complete the table to show what outputs you would expect for the two inputs.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 34 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

16 The following flowchart shows what happens when a customer uses a credit card to pay
forgoods at a supermarket. Ten of the boxes are blank.
Using the items from the list, insert the ten missing statements using the appropriatenumber
only. Each statement may be used once only.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 35 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2009. P11


9 Study the flowchart.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 36 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2010. P12


13 Study the following flowchart very carefully:

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 37 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2010. P11


4 (a)To log on to a computer, a user needs to type in a user id followed by a
password;these should match up. Only three attempts are allowed.

The flowchart below shows the log on procedure. Several boxes have been left blank.
Complete the flowchart using items from the list.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 38 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2010. P13


15 (a) The following flowchart shows how a burglar alarm system uses light sensors
todetermine if an intruder has entered the house and decides to sound an alarm.
Select statements from the list below, using numbers only, to complete the flowchart.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 39 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2011. P11


5 Study the following flowchart very carefully:

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 40 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

(b) What is the purpose of this flowchart? [1]

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 41 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2011. P12


10 The following flowchart inputs ten temperatures andoutputs the average (mean)
temperature and thenumber of temperatures which were negative (i.e. < 0).

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 42 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 43 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2011. P11

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 44 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 45 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 46 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2011. P13

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 47 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 48 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 49 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2012. P11

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 50 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 51 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 52 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 53 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2012. P12

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 54 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 55 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2012. P12

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 56 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 57 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 58 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2012. P13

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 59 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 60 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 61 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 62 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2013. P11

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 63 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 64 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2013. P12

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 65 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 66 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 67 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2013. P12

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 68 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2013. P12

5 Study the following flowchart very carefully

Complete the trace table for the following two sets of data:
(i) a = 5, b = 4, c = 1, d = 9
(ii) a = 5, b = 9, c = 4, d = 1

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 69 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

15 A library uses barcodes to identify borrowers and books. A borrower has a card
containinga barcode with an equivalent numerical code. Each book also has a
barcode with anequivalent numerical code.
The flowchart on the facing page shows what happens when book(s) are taken out
by aborrower. However, several stages are missing.
Using item numbers only, complete the flowchart by selecting stages from the item
listbelow.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 70 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 71 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2013. P13

14 A microprocessor controls the opening and closing of automatic doors to a


supermarket.Customers are detected using pressure sensors.
The flowchart on the next page shows how the sensors and microprocessor interact
tocontrol the opening and closing of the doors. However, several of the stages in the
processhave been missed out.
Using item number only, complete the flowchart using items from the following list:

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 72 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 73 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2014. P11


8 Study the following flowchart very carefully.

Complete the trace table for the input value of 5:

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 74 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

13 A heating system is being controlled by sensors and a computer. The temperature must
be keptbetween 15°C and 25°C. If 30°C is exceeded a warning message is generated and
the systemshuts down.
A flowchart of the process is shown below. Some of the items are missing.
Complete the flowchart, using item number only, from the list of items given.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 75 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2014. P12

10 Study the following flowchart very carefully.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 76 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Complete the trace table for the flowchart using the following data:
0, 3, 5, 6, -4, -1, 0, 0, -4, 10

13 An algorithm has been written to check that code numbers are valid on input. They must
be in therange 1000 to 9999.
Five hundred codes are being entered and the percentage of entered codes which are
incorrectis output.
There is a flowchart on the opposite page. It has some statements missing.
Complete the flowchart. Use statement numbers only, chosen from the list below.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 77 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2014. P12

10 (a) The flowchart on the next page shows how barcodes are used in a supermarket to
find product information and to produce orders for new stock automatically. Several
statements are missing from the flowchart.
Complete the flowchart, using item numbers only from the list below.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 78 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 79 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 80 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

14 Study the following flowchart very carefully.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 81 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2014. P13

11 An algorithm has been written to input six temperatures for every day of the year
(365 days). The
outputs are:
• the average daily temperature for each day
• the highest recorded temperature for the whole year
The algorithm is in the form of a flowchart on the next page. However, several of the
statements are missing.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 82 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Using instruction number only, complete the flowchart using the following list of
instructions:

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 83 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

13 Study the following flowchart very carefully.

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 84 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

(b) This flowchart does not give correct answers for certain sets of test data.
Suggest a data set that would give an incorrect answer.
Give a reason for your choice.
data set .....................................................................................................................................
...................................................................................................................................................
reason .......................................................................................................................................
...................................................................................................................................................
............................................................................................................................................... [2]

Unit 6- Practical problem solving – structure diagrams, algorithms and flowcharts 85 | P a g e


Unit-7:
Practical problem solving –
pseudocode
Notes for O Level Computer Science 2210 By Farhan Rahmat

Variable

A variable is a value that can change during the execution of a program.

Constant

A constant is a value that is set when the program initialises and does not change during
the program‟s execution.

Declaration

A declaration is a statement in a program that gives the compiler or the interpreter


information about a variable or constant that is to be used within a program.

A declaration ensures that sufficient memory is reserved in which to store the values and
also states the variables‟ data type. Reserved words/keywords cannot be used as identifier
names as this generates a compiler error and comes under the category of syntax error.

Declaration of local variables

DIM MyCounter AS Integer

DIM FirstName, LastName AS String „declares two variables

DIM TheLength AS Single

DIM DOB AS Date

DIM OverDueFlag AS Boolean

Scope

Scope indicates whether a variable can be used by all parts of a program or only within
limited sections of the program – for example, within a subroutine.

Global variable

A global variable is one that is declared at the start of the main program and is visible
(useable) everywhere in the program and exists for the lifetime of the program.

Note that if one procedure changes the value of a global variable, then the next
procedure that uses the variable will be given this changed value – this is a common cause
of errors.

Local variable

A local variable is one that is only visible inside the procedure or function in which it is
declared.

Note that a local variable cannot be referenced from outside the procedure. In fact a
local variable does not exist until the procedure starts executing and it disappears when
the procedure stops executing. Thus any value that is held by a local variable is only stored
temporarily.

The lifetime of a local variable is the lifetime of the procedure in which the local variable is
declared.

Unit 7- Practical problem solving – pseudocode 80 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

The advantage of using local variables rather than global variables is that the same
variable names can be used in several different procedures without any chance of values
being confused.

Using declared constants

Constants will be declared at the start of the main program. The following shows the
declaration of constants for Pi and the VAT rate

CONST Pi = 3.142

CONST VatRate = 0.175

Declaring constants at the start of a program means that maintenance is made easier for
two reasons:

• if the value of a constant changes, it only has to be changed in the one part of the
program where it has been declared, rather than in each part of the program in
which it is used;
• the code is easier to interpret:

Total=VatRate*CostPrice „allows a greater understanding than

Total=0.175*CostPrice

Unit 7- Practical problem solving – pseudocode 81 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Data types and data structures

A data type is a method of interpreting a pattern of bits.

Intrinsic data types

Intrinsic data types are the data types that are defined within a particular programming
language.

There are numerous different data types. They are used to make the storage and
processing of data easier and more efficient. Different databases and programming
systems have their own set of intrinsic data types, but the main ones are:

• Integer;
• Real;
• Boolean;
• String;
• Character;

Integer

An integer is a positive or negative number that does not contain a fractional part. Integers
are held in pure binary for processing and storage. Note that some programming
languages differentiate between short and long integers (more bytes being used to store
long integers).

Real

A real is a number that contains a decimal point. In many systems, real numbers are
referred to as singles and doubles, depending upon the number of bytes in which they are
stored.

Boolean

A Boolean is a data-type that can store one of only two values – usually these values are
True or False. Booleans are stored in one byte – True being stored as 11111111 and False as
00000000.

String

A string is a series of alphanumeric characters enclosed in quotation marks. A string is


sometimes just referred to as „text‟. Any type of alphabetic or numeric data can be stored
as a string: “Birmingham City”, “3/10/03” and “36.85” are all examples of strings. Each
character within a string will be stored in one byte using its ASCII code; modern systems
might store each character in two bytes using its Unicode. The maximum length of a string is
limited only by the available memory.
Notes:
• if dates or numbers are stored as strings then they will not be sorted correctly; they
will be sorted according to the ASCII codes of the characters – “23” will be placed
before “9”;
• telephone numbers must be stored as strings or the leading zero will be lost.

Unit 7- Practical problem solving – pseudocode 82 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Character

A character is any letter, number, punctuation mark or space, which takes up a single unit
of storage (usually a byte).

Comparison of the common data types:

Unit 7- Practical problem solving – pseudocode 83 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Define and use arrays (one- and two-dimensional) for solving simple problems (this should
include initialising arrays, reading data into arrays and performing a simple serial search on
a one-dimensional array)

A data structure is a collection of different data items that are stored together in a clearly
defined way. Two common data structures are arrays and records.

Array

An array is a data structure, which allows a set of items of identical data type to be stored
together using the same identifier name.

Arrays are declared in a similar way to standard variables, except that the array size and
dimensions are included. For example, the following declares an array that reserves five
locations in memory and labels these as „Names‟:

DIM Names(4) As String

The five individual locations are Names(0), Names(1), Names(2), Names(3), Names(4).

Each data item is called an element of the array. To reference a particular element a
programmermust use the appropriate index. For example, the following statement assigns
data to the 5thelement:

Names(4) = “Johal”

Arrays simplify the processing of similar data. An algorithm for getting five names from the
user and storing them in the array Names is shown below:

Dim Names(4) As String


For i=0 to 4
Input Value
Names(i)=Value
Next i
One-dimensional arrays

A one-dimensional array is a data structure in which the array is declared using a single
index and can be visually represented as a list.

The following diagram shows the visual representation of the array Names(4):

Unit 7- Practical problem solving – pseudocode 84 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Pseudocode

Introduction
This section covers the use of pseudocode in the production of algorithms. Students should
use standard computing text books to find out information on the features of programming
languages (high level and low level), interpreters, compilers, assemblers, user
documentation and technical documentation.

No specific programming language is referred to; development of algorithms using


pseudocode uses generic descriptions of looping, branching, data manipulation,
input/output, totaling and counting techniques.

The section is broken down into four areas:


1. description of common pseudocode terms
2. writing algorithms using pseudocode
3. finding errors in sections of pseudocode
4. exercises

Definition
An algorithm is a procedure for solving a problem in terms of the actions to be executed
and the order in which those actions are to be executed. An algorithm is merely the
sequence of steps taken to solve a problem. The steps are normally "sequence," "selection,
" "iteration," and a case-type statement.

The "selection" is the " if ….. then ….. else ….. endif" statement, and the iteration is satisfied
by a number of statements, such as the " for … to … next, while … endwhileand repeat …
until " while the case-type statement is satisfied by the " case of ….. otherwise …... endcase"
statement.

Common pseudocode terms

1.1 counting
Counting in 1s is quite simple; use of the statement count  count + 1 will enable counting
to be done (e.g. in controlling a repeat loop). The statement literally means: the (new)
count =the (old) count + 1

It is possible to count in any increments just by altering the numerical value in the statement
(e.g. count  count – 1 counts backwards)

1.2 totalling
To add up a series numbers the following type of statement should be used:

total total + number

This literally means (new) total = (old) total + value of number

1.3 input/output
Input and output indicated by the use of the terms READ number, PRINT total, PRINT “result
is” x and so on.

Unit 7- Practical problem solving – pseudocode 85 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

1.4 branching
There are two common ways of branching:
case of ….. otherwise …... endcase
if ….. then ….. else ….. endif

case of if … then
casenumber of if number = 1 then x  x + 1
1: x  x + 1 else if number = 2 then y  y + 1
2: y  y + 1 else print “error”
otherwise print “error” endif
endcase endif

1.5 loops
There are three common ways of performing a looping function:

for … to … next, while … endwhileand repeat … until

The following example input 100 numbers and finds the total of the 100 numbers and
outputs this total. All three looping techniques are shown:

for … to while … endwhile repeat … until


forcount  1 to 100 while count < 101 repeat
inputnumber input number input number
totaltotal+number totaltotal+number totaltotal+number
next count  count + 1 count  count + 1
printtotal endwhile until count = 100
printtotal print total

Understand and use assignment statements

Assignment
An assignment is an instruction in a program that places a value into a specified variable.
Some typical assignments are:

TheLength 20.5
TheUsersName$ “Charlie”
TheAreaTheWidth * TheLength
TotalCostLabelledCost + 15
Counter  Counter + 1

Note that the last example is a common method used to increment the value of a
variable. It could be read as:

“The new value of Counter is its existing value plus one”

Unit 7- Practical problem solving – pseudocode 86 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Arithmetic operators including operators for integer

Addition, subtraction and multiplication

Division

Relational operators, eg. =, <, <=, >, >= and <>

Relational operators are used in the format: [Expression] [Operator] [Expression] and will
always return a Boolean (True or False) value.

Relational operators are typically used with the IF selection and also within conditional
loops
(REPEAT-UNTIL or WHILE-WEND).

In the following table, the variables a and name$ have the following assignments:

a3+5
name$ “JAMES”

Unit 7- Practical problem solving – pseudocode 87 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Boolean operators AND, OR and NOT


AND and OR
The AND and OR operators always return a Boolean result and are used in the format:

[Boolean] [Operator] [Boolean]

The following „truth‟ table summarises the result of the Boolean operations:

Values Results

NOT
The NOT operator reverses the result of the Boolean expression and is used in the format:

NOT [Boolean]

The following truth table summarises the NOT operation:

Examples of Boolean „logic‟


Consider the following algorithm, which is used to monitor a printer and display its output
via an
LCD display in the front panel:

IF NOT(PaperTrayEmpty) AND (FilesWaiting> 0) THEN


OUTPUT “PRINTING…”
ELSE
OUTPUT “PLEASE ADD PAPER”
END IF

Unit 7- Practical problem solving – pseudocode 88 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Validation

The drop-down lists, check-boxes and option buttons are extremely useful in that they
provide an automatic means of validation – the user can only input pre-determined values.

Other validation needs to be programmed into the system and is often added to the
submit button.

Presence check

Code can be added to check that a particular control has not been left empty or un-
checked:

If Username = “” Then

Print (“You have not entered a Username”)

End

Range check

Code can be added to check that a particular control has a value between an allowed
maximum and minimum:

If Age < 11 OR Age > 70 Then

Print (“The age that you have netered is not within the_

permitted range”)

End

Length check

Code can be added to check that a particular control has a value between an allowed
maximum and minimum:

If Len(Password) > 12 Then

Print (“The password that you have entered is too long”)

End

Unit 7- Practical problem solving – pseudocode 89 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Writing algorithms using pseudocode


The following five examples use the above pseudocode terms. These are the same
problems discussed in section 3.1 using flow charts – both methods are acceptable ways of
representing an algorithm.

2.1 Example 1
A town contains 5000 houses. Each house owner must pay tax based on the value of the
house. Houses over $200 000 pay 2% of their value in tax, houses over $100 000 pay 1.5% of
their value in tax and houses over $50 000 pay 1% of their value in tax. All others pay no tax.
Write an algorithm to solve the problem using pseudocode.
forcount  1 to 5000
inputhouse
ifhouse > 50 000 then tax  house * 0.01
else if house > 100 000 then tax  house * 0.015
else if house > 200 000 then tax  house * 0.02
elsetax  0
printtax
next

Notes:
(1) awhile loop or a repeat loop would have worked just as well
(2) the use of endifisn‟t essential in the pseudocode

For example,

count 0
whilecount < 5001
inputhouse
ifhouse > 50000 then tax  house * 0.01
else if house > 100 000 then tax  house * 0.015
else if house > 200 000 then tax  house * 0.02
elsetax  0
endif
endif
endif
printtax
count count + 1
endwhile

EXERCISE: Re-write the above algorithm using a repeat loop and modify the if … then …
else statements to include both parts of the house price range.
(e.g. if house > 50000 and house <= 100000 then tax = house * 0.01)

Unit 7- Practical problem solving – pseudocode 90 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

2.2 Example 2
The following formula is used to calculate n: n = x * x/(1 – x)
The value x = 0 is used to stop the algorithm. The calculation is repeated using values of x
until the value x = 0 is input. There is also a need to check for error conditions. The values of
n and x should be output.

Write an algorithm to show this repeated calculation using pseudocode.

NOTE: It is much easier in this example to input x first and then loop round doing the
calculation until eventually x = 0. Because of this, it would be necessary to input x twice (i.e.
inside the loop and outside the loop). If input x occurred only once it would lead to a more
complicated algorithm.

(Also note in the algorithm that <> is used to represent ≠ ).

A while loop is used here, but a repeat loop would work just as well.

inputx
whilex <> 0 do
ifx = 1 then print “error”
elsen  (x * x)/(1 – x)
printn, x
endif
inputx
endwhile

2.3 Example 3
Write an algorithm using pseudocode which takes temperatures input over a 100 day
period (once per day) and output the number of days when the temperature was below
20C and the number of days when the temperature was 20C or above.

(NOTE: since the number of inputs is known, a for … to loop can be used. However, a while
loop or a repeat loop would work just as well).

total1  0: total2  0
fordays  1 to 100
inputtemperature
iftemperature < 20 then total1  total1 + 1
elsetotal2  total2 + 1
endif
next
printtotal1, total2

This is a good example of an algorithm that could be written using the case construct
rather than if … then … else. The following section of code replaces the statements if
temperature < 20 then …… endif:
casetemperature of
1: total1 = total1 + 1
2: total2 = total2 + 1
endcase

Unit 7- Practical problem solving – pseudocode 91 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

2.4 Example 4
Write an algorithm using pseudocode which:

 inputs the top speeds of 5000 cars


 outputs the fastest speed and the slowest speed
 outputs the average speed of all the 5000 cars

(NOTE: Again since the actual number of data items to be input is known any one of the
three loop structures could be used. It is necessary to set values for the fastest (usually set at
zero) and the slowest (usually set at an unusually high value) so that each input can be
compared. Every time a value is input which > the value stored in fastest then this input
value replaces the existing value in fastest; and similarly for slowest).

fastest 0: count  0
slowest 1000
repeat
inputtop_speed
total total + top_speed
iftop_speed> fastest then fastest top_speed
iftop_speed< slowest then slowest top_speed
endif
endif
count count + 1
untilcount = 5000
average total * 100/5000
printfastest, slowest, average

Unit 7- Practical problem solving – pseudocode 92 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

2.5 Example 5
A shop sells books, maps and magazines. Each item is identified by a unique 4 – digit code.
All books have a code starting with a 1, all maps have a code starting with a 2 and all
magazines have a code beginning with a 3. The code 9999 is used to end the program.

Write an algorithm using pseudocode which input the codes for all items in stock and
outputs the number of books, maps and magazine in stock. Include any validation checks
necessary.

(NOTE: A 4-digit code implies all books have a code lying between 1000 and 1999, all maps
have a code lying between 2000 and 2999 and all magazines a code lying between 3000
and 3999. Anything outside this range is an error)

books 0: maps  0: mags 0


repeat
inputcode
ifcode > 999 and code < 2000 then books  books + 1
else if code > 1999 and code < 3000 then maps  maps + 1
else if code > 2999 and code < 4000 then magsmags + 1
else print “error in input”
endif:endif:endif
untilcode = 9999
printbooks, maps, mags

(NOTE: A function called INT(X) is useful in questions like this. This returns the integer (whole
number) part of X e.g. if X = 1.657 then INT(X) = 1; if X = 6.014 then INT(X) = 6 etc. Using this
function allows us to use the case statement to answer this question:

books 0: maps  0: mags 0


repeat
inputcode
x INT(code/1000)
casex of
1: books  books + 1
2: maps  maps + 1
3: magsmags + 1
otherwise print “error”
endcase
untilcode = 9999
printbooks, maps, mags

(this is probably a more elegant but more complex solution to the problem)

Unit 7- Practical problem solving – pseudocode 93 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Finding and correcting errors in pseudocode algorithms:

Common errors in pseudocode algorithms include:

 Missing or faulty initialization of variables;


(all numerical variables will be initialized with 0 except for Min/Lowest/Shortest and
variable directly involved in Division and Multiplication after initialization. Min Lowest,
Shortest will be initialized with high value i.e. 1000 and variable directly involved in
Division and Multiplication will be initialized with 1.)
 Faulty initial and final values for the control variable or “loop counter” in a For…Next
loop;
(if 100 iteration is required then FOR Count0 to 100 would be wrong as it will repeat 101
times, it should be FOR Count1 to 100)
 Increment the loop counter in For…Next loop, which interferes with the automatic
counting;
(Never place Count Count+1 inside FOR…NEXT loop, it will be done automatically.)
 Failing to increment a counter variable in the other sorts of loop;
(Never forget to place Count Count+1 in REPEAT…UNTIL and WHILE…ENDWHILE loop if
you implement count based loop with REPEAT…UNTIL and WHILE…ENDWHILE instead of
FOR…NEXT.)
 Failing to complete a structure statement with the requisite ending keyword: ENDWHILE,
UNTIL, NEXT, ENDIF or ENDCASE.
 Misplacing a keyword, so that statements are inappropriately inside or outside a loop.
(Never print Total/Counting variable/Extreme values/Average inside the loop, only result
of any calculation will be print inside the loop.)

Example:
Line 1 Max0
Line 2 Min0
Line 3 FOR Count25 to 1
Line 4 REPEAT
Line 5 OUTPUT “Please enter a Mark between 0 and 100”
Line 6 INPUT Mark
Line 7 UNTIL Mark >=0 AND Mark<=50
Line 8 IF Mark > Max THEN Max Mark
Line 9 IF Mark < Min THEN Min Mark
Line 10 Count Count+1
Line 11 TotalTotal+Mark
Line 12 AvgTotal/25
Line 13 OUTPUT “Maximum Mark: “, Max
Line 14 OUTPUT “Minimum Mark: “, Min
Line 15 OUTPUT “Mean Mark: “, Avg

Line Number Error Correction

11 Total not initialized before Insert Total0 before line 1


use

2 Min initialized to too low a Amend to Min1000


value

Unit 7- Practical problem solving – pseudocode 94 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

3 Reversed initial and final Amend to FOR Count1


value for Count. to 25

10 Count Count+1interferes Delete line 10.


with the automatic
counting in the FOR Loop.

12 FOR loop not complete Insert NEXT before line 12


before output start

Past Papers Questions:

Oct/Nov 2006
9 A computer program is required which inputs 10 numbers, multiplies them together and
finally outputs the answer (the product). The following algorithm has been written to do this.

1 count = 0
2 product = 0
3 while count <= 10 do
4 input number
5 product = product * number
6 count = count + 1
7 print product
8 endwhile

(a) There are three errors in the algorithm. Locate and describe these errors. [3]
(b) A while … do loop has been used in the algorithm. State another type of loop that
could have been used. [1]

May/June 2010. P11


12 A golf course charges $10 for each game of two people. Each additional person incurs
afurther charge of $2 per game. If they book two or more games in advance, they get a
10%discount on the total charge.
The following program has been written in pseudocode to calculate the charges for a
game.
1 extracost = 0
2 input numberpeople, numbergames
3 charge = 10 * numbergames
4 extrapeople = numberpeople – 2
5 if numberpeople< 2 then extracost = 2 * extrapeople * numbergames
6 charge = extracost
7 if numbergames> 1 then charge = charge * 0.1
8 print charge
There are three errors in the program. Locate these errors and suggest a correct piece
ofcoding. [6]

Unit 7- Practical problem solving – pseudocode 95 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2010. P11


9 The following algorithm inputs 20 numbers and outputs how many numbers were positive
(> 0) and how many numbers were negative (< 0).

1 negative = 1
2 positive = 1
3 for count = 1 to 20 do
4 input number
5 if number < 0 then negative = negative + 1
6 if number > 0 then positive = positive + 1
7 count = count + 1
8 print negative, positive
9 next count

There are three different errors in this algorithm.


Locate each error and give the reason why you think it is an error. [6]

May/June 2011 P12


7 (a) Read the following section of code that inputstwenty (20) numbers and then outputs
the largestnumber input.
1h=0
2c=0
3 REPEAT
4 READ x
5 IF x > h THEN x = h
6c=c+1
7 PRINT h
8 UNTIL c < 20
There are THREE errors in this code.
Locate these errors and suggest a corrected pieceof code. [3]

Oct/Nov 2013. P12

8 A piece of pseudocode was written to input 1000 positive numbers and then output
thehighest and lowest numbers.
10 highest = 0
20 lowest = 0
30 for count = 1 to 100
40 input number
50 if number > highest then number = highest
60 if number < lowest then number = lowest
70 count = count + 1
80 next count
90 print highest, lowest

There are errors in the code.


Locate these errors and suggest a correction. [8]

Unit 7- Practical problem solving – pseudocode 96 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2014 P12

5 The following algorithm should:


• input ten numbers
• output the largest number input
• output the average value of the input data
10 largest = 0
20 sum = 0
30 for x = 1 to 10
40 input x
50 if x > largest then x = largest
60 output largest
70 sum = sum + x
80 next x
90 average = sum * 10
100 output average
There are four errors in this algorithm.
Locate these errors and suggest a correction.

Oct/Nov 2014. P12

6 The following section of a pseudocode algorithm should:


• input 500 numbers
• generate a ratio called k
• output each value of k
• output how many numbers were larger than 10
10 total = 1
20 FOR x = 1 TO 500
30 IF number < 10 THEN total = total + 1
40 k = x / number
50 x=x+1
60 OUTPUT k
70 NEXT x
80 OUTPUT x
(a) There are five errors in the above code.
Locate these errors and suggest a correction.
error 1 .......................................................................................................................................
correction ..................................................................................................................................
...................................................................................................................................................
error 2 .......................................................................................................................................
correction ..................................................................................................................................
...................................................................................................................................................
error 3 .......................................................................................................................................
correction ..................................................................................................................................
...................................................................................................................................................
error 4 .......................................................................................................................................
correction ..................................................................................................................................
...................................................................................................................................................
error 5 .......................................................................................................................................

Unit 7- Practical problem solving – pseudocode 97 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

correction ..................................................................................................................................
............................................................................................................................................... [5]

(b) The corrected algorithm was converted to a computer program and run. However,
after several numbers were input, the program stopped and an error message was
generated, showing that there was a further error at line 40 (k = x / number).
State what could cause this error to occur.
...................................................................................................................................................
...................................................................................................................................................
Suggest a change to line 40 to overcome this problem.
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................... [2]

Oct/Nov 2014. P13

6 The following pseudocode algorithm should:


• input up to 20 numbers
• stop if the sum of the input numbers exceeds 50
• output the final sum
10 count = 0
20 REPEAT
30 INPUT n
40 n + sum = sum
50 IF sum = 50 THEN count = 20
60 count = count + 1
70 UNTIL count = 20
80 OUTPUT n
There are five errors in this algorithm.
Locate these errors and suggest a correction.
error 1 .......................................................................................................................................
correction ..................................................................................................................................
...................................................................................................................................................
error 2 .......................................................................................................................................
correction ..................................................................................................................................
...................................................................................................................................................
error 3 .......................................................................................................................................
correction ..................................................................................................................................
...................................................................................................................................................
error 4 .......................................................................................................................................
correction ..................................................................................................................................
...................................................................................................................................................
error 5 .......................................................................................................................................
correction ..................................................................................................................................
............................................................................................................................................... [5]

Unit 7- Practical problem solving – pseudocode 98 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Array

Question 01: Input and store the names and marks for 30 students who have sat three
computer science tests.Test 1 is out of 20 marks, Test 2 is out of 25 marks, Test 3 is out of 35
marks. You must store thenames in a one-dimensional array and the marks and total score
for each student in one-dimensionalarrays. All the marks must be validated on entry and
any invalid marks rejected. You may assumethat the students‟ names are unique.

Question 02: Calculate and store the total score for each student and calculate the
average score for the wholeclass. Output each student‟s name followed by their total
score, then output the average score for theclass.

Question 03: Select the student with the highest score and output their name and score.
Your program must include appropriate prompts for the entry of data. Error messages and
otheroutput need to be set out clearly and understandably. All variables, constants and
other identifiersmust have meaningful names. Each task must be fully tested.

Question 04: Write a pseudocode using array, asks user to input 10 numbers, then
calculates the average of those numbers. Loop is used in this problem.

Question 05: Write a pseudocode to swap first and last element of an integer 1-d array.

Question 06: Write a pseudocode to find the largest and smallest element of an array.

Unit 7- Practical problem solving – pseudocode 99 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Practice Questions:
Questions 1 to 3 contain sections of pseudocode which contain errors. Locate the errors
and suggest the correct coding. Questions 4 to 10 are problems which require an algorithm
to be written in pseudocode – there is “no right answer” here; as long as the pseudocode
works then the solution is acceptable.

(1) The following section of pseudocode inputs 1000 numbers and then outputs how many
were negative, how many were positive and how many were zero.
Locate the 3 errors and suggest a corrected piece of code.

1 negative  1: positive  1
2 for x  0 to 1000
3 input number
4 if number < 0 then negative  negative + 1
5 if number > 0 then positive  positive + 1
6 endif
7 endif
8 next
9 print negative, positive

(2) The following section of pseudocode inputs rainfall (in cm) for 500 days and outputs the
average rainfall and the highest rainfall input.
Locate the 3 errors and suggest a corrected piece of code.

1 highest  1000
2 days  1
3 while days > 0
4 input rainfall
5 if rainfall > highest then highest  rainfall
6 endif
7 total  total + rainfall
8 days  days + 1
9 average  total/500
10 endwhile
11 print average, highest

(3) The following section of pseudocode inputs a number, n, multiplies together 1 x 2 x 3 x


……. x n, calculates input number/sum and outputs result of the calculation.
Locate the 3 errors and suggest a corrected piece of code.

1 input n
2 for mult 1 to n
3 sum  0
4 sum  sum * mult
5 result  n/sum
6 next
7 print result

(4) Regis lives in Brazil and often travels to USA, Europe and Japan. He wants to be able to
convert Brazilian Reais into US dollars, European euros and Japanese yen. The conversion
formula is:

currency value = number of Reais X conversion rate


For example, if Regis is going to USA and wants to take 1000 Reais (and the exchange rate
is 0.48) then he would input USA, 1000 and 0.48 and the output would be: 480 US dollars.

Unit 7- Practical problem solving – pseudocode 100 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Write an algorithm, using pseudocode, which inputs the country he is visiting, the exchange
rate and the amount in Brazilian Reais he is taking. The output will be value in foreign
currency and the name of the currency.

(5) As part of an experiment, a school measured the heights (in metres) of all its 500
students.
Write an algorithm, using pseudocode, which inputs the heights of all 500 students and
outputs the height of the tallest person and the shortest person in the school.

(6) A geography class decide to measure daily temperatures and hours of sunshine per
day over a 12 month period (365 days)

Write an algorithm, using pseudocode, which inputs the temperatures and hours of
sunshine for all 365 days, and finally outputs the average (mean) temperature for the year
and the average (mean) number of hours per day over the year.

(7) A small shop sells 280 different items. Each item is identified by a 3 – digit code. All items
that start with a zero (0) are cards, all items that start with a one (1) are sweets, all items
that start with a two (2) are stationery and all items that start with a three (3) are toys.

Write an algorithm, using pseudocode, which inputs the 3 – digit code for all 280 items and
outputs the number of cards, sweets, stationery and toys.

(8) A company are carrying out a survey by observing traffic at a road junction. Each time
a car, bus, lorry or other vehicle passed by the road junction it was noted down.
10 000 vehicles were counted during the survey.
Write an algorithm, using pseudocode, which:
 inputs all 10000 responses
 outputs the number of cars, buses and lorries that passed by the junction during the
survey
 outputs the number of vehicles that weren’t cars, buses or lorries during the survey

(9) Speed cameras read the time a vehicle passes a point (A) on the road and then reads
the time it passes a second point (B) on the same road (points A and B are 100 metres
apart). The speed of the vehicle is calculated using:

The maximum allowed speed is 100 kilometres per hour. 500 vehicles were monitored using
these cameras over a 1 hour period.
Write an algorithm, using pseudocode, which:
 inputs the start time and end time for the 500 vehicles that were monitored
 calculate the speed for each vehicle using the formula above
 outputs the speed for each vehicle and also a message if the speed exceeded 100
km/hour
 output the highest speed of all the 500 vehicles monitored
(10) There are ten stations on a railway line:

1 ------ 2 ------ 3 ------ 4 ------ 5 ------ 6 ------ 7 ------ 8 ------ 9 ------ 10

The train travels in both directions (i.e. from 1 to 10 and then from 10 to 1). The fare
between each station is $2.
A passenger inputs the number of the station at the start of his journey and the number of
the destination station and the fare is calculated (e.g if a passenger gets on a station 3 and
his destination is station 9 his fare will be $12). The calculation must take into account the
direction of the train (e.g. a passenger getting on at station 7 and getting off at station 1
will also pay $12 and not a negative value!!).

Unit 7- Practical problem solving – pseudocode 101 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

A discount of 10% is given if 3 or more passengers are travelling together.

Write an algorithm, using pseudocode, which:


 inputs the number of passengers travelling
 inputs the station number of the starting point and the station number of the
destination
 calculates the total fare taking into account the direction of travel
 calculates any discount due
 outputs the cost of the tickets and prints the tickets

100
𝑠𝑝𝑒𝑒𝑑 = (𝑚𝑒𝑡𝑒𝑟𝑠/𝑠𝑒𝑐𝑜𝑛𝑑)
(time at point B – time at point A)

The maximum allowed speed is 100 kilometres per hour. 500 vehicles were monitored using
these cameras over a 1 hour period.

Write an algorithm, using pseudocode, which:


 inputs the start time and end time for the 500 vehicles that were monitored
 calculate the speed for each vehicle using the formula above
 outputs the speed for each vehicle and also a message if the speed exceeded 100
km/hour
 output the highest speed of all the 500 vehicles monitored

(10) There are ten stations on a railway line:

1 ------ 2 ------ 3 ------ 4 ------ 5 ------ 6 ------ 7 ------ 8 ------ 9 ------ 10

The train travels in both directions (i.e. from 1 to 10 and then from 10 to 1). The fare
between each station is $2.

A passenger inputs the number of the station at the start of his journey and the number of
the destination station and the fare is calculated (e.g if a passenger gets on a station 3 and
his destination is station 9 his fare will be $12). The calculation must take into account the
direction of the train (e.g. a passenger getting on at station 7 and getting off at station 1
will also pay $12 and not a negative value!!).

A discount of 10% is given if 3 or more passengers are travelling together.

Write an algorithm, using pseudocode, which:


 inputs the number of passengers travelling
 inputs the station number of the starting point and the station number of the
destination
 calculates the total fare taking into account the direction of travel
 calculates any discount due
 outputs the cost of the tickets and prints the tickets

Unit 7- Practical problem solving – pseudocode 102 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Past Papers Questions:


May/June 2006
16 (a) A formula for calculating the body mass index (BMI) is:

Calculate the BMI for a person whose weight is 80kg and height is 2 metres. [1]

(b) Using pseudocode or otherwise, write an algorithm that will input the ID, weight (kg)
and height (m) of 30 students, calculate their body mass index (BMI) and output their ID,
BMI and a comment as follows:

A BMI greater than 25 will get the comment „OVER WEIGHT‟, a BMI between 25 and 19
(inclusive) will get „NORMAL‟ and a BMI less than 19 will get „UNDER WEIGHT‟. [6]

20 Temperatures (°C) are being collected in an experiment every hour over a 200 hour
period. Write an algorithm, using pseudocode or otherwise, which inputs each temperature
and outputs
• how many of the temperatures were above 20°C
• how many of the temperatures were below 10°C
• the lowest temperature that was input [5]

May/June 2007
19 A company has 5000 CDs, DVDs, videos and books in stock. Each item has a unique5-
digit code with the first digit identifying the type of item, i.e.
1 = CD
2 = DVD
3 = video
4 = book
For example, for the code 15642 the 1 identifies that it is a CD, and for the code 30055 the3
identifies that it is a video.
Write an algorithm, using pseudocode or otherwise, that
• Inputs the codes for all 5000 items
• Validates the input code
• Calculates how many CDs, DVDs, videos and books are in stock
• Outputs the four totals. [5]

Oct/Nov 2007
16 (a) Fuel economy for a car is found using the formula:

What would be the Fuel Economy of a car travelling 40 km on 10 litres of fuel? [1]

(b) The Fuel Economy for 1000 cars is to be calculated using the formula in Question 16(a).
Write an algorithm, using pseudocode or otherwise, which inputs the Distance Travelled
(km) and the Fuel Used (litres) for 1000 cars. The Fuel Economy for each car is then
calculated and the following outputs produced:
• Fuel Economy for each car
• average (mean) Fuel Economy for all of the cars input
• the best Fuel Economy (i.e. highest value)
• the worst Fuel Economy (i.e. lowest value) [6]

Unit 7- Practical problem solving – pseudocode 103 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2008

12 Algorithms and programs use loops to control the number of times a particular
procedure isused.
Two methods are repeat … until and for … to.
(a) Write a procedure using both these loop methods to input 20 numbers into a
variablecalled x.
(i) repeat … until [2]
(ii) for … to [2]
(b) Name another loop structure. [1]

19 Customers can withdraw cash from an Automatic Teller Machine (ATM).


• withdrawal is refused if amount entered > current balance
• withdrawal is refused if amount entered > daily limit
• if current balance < $100, then a charge of 2% is made
• if current balance $100, no charge is made
Write an algorithm which inputs a request for a sum of money, decides if a withdrawal can
be made and calculates any charges. Appropriate output messages should be included.
[5]

Oct/Nov 2008
19 The manufacturing cost of producing an item depends on its complexity. A company
manufactures three different types of item, with costs based on the following calculations:

Item type 1: item cost = parts cost * 1.5


Item type 2: item cost = parts cost * 2.5
Item type 3: item cost = parts cost * 5.0
The company makes 1000 items per day.

Write an algorithm, using pseudocode, flowchart or otherwise, which


• inputs the item type and parts cost of each item
• outputs the item cost for each item
• calculates and outputs the average (mean) item cost per day (based on 1000 items
being made). [5]

May/June 2009
18 A small airport handles 400 flights per day from three airlines:
FASTAIR (code FA)
SWIFTJET (code SJ)
KNIGHTAIR (code KA)
Each flight is identified by the airline code and 3 digits. For example FA 156.
Write an algorithm, using pseudocode or otherwise, which monitors the 400 flights into and
out of the airport each day. The following inputs, processing and outputs are all part of the
monitoring process:
• input flight identification
• calculate number of flights per day for each of the three airlines
• output the percentage of the total flights per day by each airline
• any validation checks must be included [5]

Unit 7- Practical problem solving – pseudocode 104 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2009. P11


17 (a) A car‟s speed is measured between points A and B, which are 200 km apart.

The final speed of the car is calculated using the formula:

What is the final speed of a car if it takes 2 hours to get from A to B? [1]

(b) Write an algorithm, using pseudocode or otherwise, which inputs the times for 500 cars,
calculates the final speed of each car using the formula in part (a), and then outputs:
• the final speed for ALL 500 cars
• the slowest (lowest) final speed
• the fastest (highest) final speed
• the average final speed for all the cars. [6]

May/June 2010. P11


18 A group of students were monitoring the temperature every day over a one-year period.
Readings were taken ten times every day (you may assume a year contains 365 days).

Write an algorithm, using pseudocode or flowchart, which


• inputs all the temperatures (ten per day)
• outputs the highest temperature taken over the year
• outputs the lowest temperature taken over the year
• outputs the average temperature per day
• outputs the average temperature for the whole year [7]

May/June 2010. P12


16 (a) Write an algorithm, using pseudocode or a flowchart, which:
• inputs 50 numbers
• outputs how many of the numbers were > 100 [3]

(b) Write an algorithm, using pseudocode or a flowchart, which:


• inputs 100 numbers
• finds the average of the input numbers
• outputs the average [3]

Oct/Nov 2010. P12


17 A school is doing a check on the heights and weights of all its students. The school has
1000 students.
Write an algorithm, using pseudocode or a flowchart, which
• inputs the height and weight of all 1000 students
• outputs the average (mean) height and weight
• includes any necessary error traps for the input of height and weight [5]

Oct/Nov 2010. P13


17 (a) Write an algorithm, using pseudocode or a flowchart, which
• inputs a set of positive numbers (which end with -1)
• outputs the average (mean) value of the input numbers
• outputs the value of the largest (highest) number input [4]

Unit 7- Practical problem solving – pseudocode 105 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

(b) Write an algorithm, using pseudocode or a flowchart, which


• inputs a whole number (which is > 0)
• calculates the number of digits in the number
• outputs the number of digits and the original number
(E.g. 147 would give an output of 3, 147) [4]

May/June 2011. P11


17 Daniel lives in Italy and travels to Mexico, India and New Zealand. The times differences
are:

Country Hours Minutes


Mexico -7 0
India +4 +30
New Zealand +11 0

Thus, if it is 10:15 in Italy it will be 14:45 in India.

(a) Write an algorithm, using pseudocode or otherwise, which:


• Inputs the name of the country
• Inputs the time in Italy in hours (H) and minutes (M)
• Calculates the time in the country input using the data from the table
• Outputs the country and the time in hours and minutes [4]

(b) Describe, with examples, two sets of test data you would use to test your algorithm.
[2]

May/June 2011. P12


17 A school has 1800 students. The start date and leaving date for each student is stored on
file. Dates are in the format YYMMDD (e.g. a student starting on 10th September 2007 and
leaving on 4th August 2012 has the data 070910 and 120804 on file).
(a) Write an algorithm, using pseudocode or otherwise, which
• inputs Student ID for all 1800 students
• inputs the start date and leaving date for each student
• carries out a check to ensure the second date is later
• if error, increments error counter
• outputs the number of errors [5]

(b) Describe, with examples, TWO sets of test data you would use to test your algorithm.
[2]

Oct/Nov 2011. P11


17 (a) Write an algorithm, using pseudocode or flowchart only, which:
• inputs three numbers
• outputs the largest of the three numbers

(b) Write an algorithm, using pseudocode or flowchart only, which:


• inputs 1000 numbers
• outputs how many of these numbers were whole numbers (integers)
(You may use INT(X) in your answer e.g. Y = INT(3.8) gives the value Y = 3)

Unit 7- Practical problem solving – pseudocode 106 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2011. P13


16 The weather conditions in a town are being monitored over a year (365 days). The
valuesrecorded per day are weather type and temperature (e.g. CLOUDY, 25).
Write an algorithm, using pseudocode or flowchart only, which:
• inputs the weather type and temperature for each day
• outputs the number of days that were CLOUDY, RAINING, SUNNY or FOGGY
• outputs the highest recorded temperature for the year
• outputs the lowest recorded temperature for the year

May/June 2012. P11


17 Write an algorithm, using pseudocode or a program flowchart only, which:
• inputs the population and land area for 500 countries,
• calculates the population density (i.e. population/land area) for every country,
• outputs the largest and smallest population density,
• outputs the average population for all 500 countries. [6]

May/June 2012. P12


15 An estate agent advertises houses for sale. The customer enquiries for a 7-day
workingweek are entered weekly into a computer.
Write an algorithm, using pseudocode or a program flowchart only, which:
• inputs the number of customer enquiries each day,
• inputs the house price each customer enquires about,
• outputs how many customers enquired each day about houses costing less than
$100 000,
• outputs the percentage of all enquiries made during the week about houses costingmore
than $500 000. [6]

Oct/Nov 2012. P12

17 (a) Write an algorithm, using pseudocode or a program flowchart only, that:


• inputs a series of positive numbers (-1 is used to terminate the input),
• outputs how many numbers were less than 1000 and
• outputs how many numbers were greater than 1000. [4]

(b) Write an algorithm, using pseudocode or a program flowchart only, that


• inputs fifty numbers each as 4 separate digits, for example: 1 5 4 1
• outputs the percentage of numbers that were palindromes.
(note: a palindrome reads the same way backwards or forwards. For example, 1331 isa
palindrome but 1541 is not).
Use separate variables to store the separate digits of a number (for example D1, D2,
D3, D4). [4]

Oct/Nov 2012. P13


16 A small café sells five types of item:
bun 0.50 dollars
coffee 1.20 dollars
cake 1.50 dollars
sandwich 2.10 dollars
dessert 4.00 dollars
Write an algorithm, using pseudocode or a program flowchart only, which
• inputs every item sold during the day,
• uses an item called “end” to finish the day‟s input,
• adds up the daily amount taken for each type of item,
• outputs the total takings (for all items added together) at the end of the day,
• outputs the type of item that had the highest takings at the end of the day. [4]

Unit 7- Practical problem solving – pseudocode 107 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2013. P11

2 Name two different types of loop structure in a typical programming language.


Give an example of how ten numbers could be input using the named loop. [6]

16 A small shop uses barcodes which represent 5 digits. The last digit is used as a check
digit.
For example:
abcde
01234
The check digit (e) is found by:
• multiplying the first and third digits (i.e. a and c) by 3
• multiplying the second and fourth digits (i.e. b and d) by 2
• adding these four results together to give a total
• dividing this total by 10
• remainder is check digit (e)
Write an algorithm, using pseudocode or flowchart only, which
• inputs 100 five-digit barcodes in the form a, b, c, d, e
• re-calculates the check digit for each number and checks whether the input check
digit(e) is correct
• outputs the number of barcodes which were entered correctly [5]

May/June 2013. P12

17 A country has four mobile phone network operators. Each mobile phone number has
eightdigits. The first three digits identify the network operator:
444 Yodafone
555 N2 network
666 Kofee mobile
777 Satsuma mobile
Write an algorithm, using pseudocode or flowchart only, which reads 50 000 eight-
digitmobile phone calls made during the day and outputs the number of calls made on
each ofthe four networks. [6]

Oct/Nov 2013. P12

16 (a) A greenhouse is being monitored by a computer using 2 sensors. SENSOR1


measuresthe temperature and SENSOR2 measures oxygen levels.
If the temperature exceeds 45°C or oxygen levels fall below 0.19, then an errormessage is
output by the computer.
Write an algorithm, using pseudocode or flowchart only, which
• inputs both sensor readings
• checks the sensor input values and outputs a warning message if either are out of
range
• continues monitoring until the <ESCAPE> key is pressed
(You may assume that READ SENSORn will take a reading from SENSORn and that
READ KEY inputs a key press from the keyboard). [5]

Unit 7- Practical problem solving – pseudocode 108 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2013. P13

10 (a) The following pseudocode was written to input 1000 dates.


1 count = 1
2 repeat
3 input day, month, year
4 count = count + 1
5 until count = 1000
(i) Describe why the loop only inputs 999 dates instead of 1000. [1]
(ii) What needs to be changed or added to the above code to make sure 1000 dates
are input? [1]
(b) Errors in code can be found using test data.
Name three different types of test data. Using month from the pseudocode above, give
an example of each type of test data. [6]

15 5000 numbers are being input which should have either 1 digit (e.g. 5), 2 digits (e.g. 36),
3digits (e.g. 149) or 4 digits (e.g. 8567).
Write an algorithm, using pseudocode or flowchart only, which
• inputs 5000 numbers
• outputs how many numbers had 1 digit, 2 digits, 3 digits and 4 digits
• outputs the % of numbers input which were outside the range [6]

May/June 2014. P11

15 A survey is being carried out which involves reading and recording sound levels near a
busy roadjunction. Once all the data are collected, they are input manually into a
computer. A sound levelof 0 decibels (0 dB) is input to indicate the end of the data.
Write an algorithm, using pseudocode or a flowchart, which:
• inputs all the sound levels
• after a sound level of 0 is input, outputs the following:
o average sound level
o highest recorded sound level.

May/June 2014 P12

18 A school has 1500 students. It is conducting a survey on their music preferences. Each
studentuses a computer and inputs their name and then chooses one of 5 options:
• rock (input value 1)
• soul (input value 2)
• pop (input value 3)
• jazz (input value 4)
• classical (input value 5)
Write an algorithm, using pseudocode or a flowchart, which:
• inputs the choice of all 1500 students (values 1 to 5)
• outputs all the names of the students who chose classical music
• outputs the percentage who chose each option.

Oct/Nov 2014. P12


16 A school has 3000 students sitting final examinations.
Each student sits eight examinations.
Write an algorithm, using pseudocode or a flowchart, which:
• inputs the marks for all 8 examinations for each student
• outputs for each student the average mark for their 8 examinations
• outputs the highest mark overall [5]

Unit 7- Practical problem solving – pseudocode 109 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2014. P12

16 A customer wants to compare prices of 1000 items sold in two supermarkets (price1 and
price2).
Write an algorithm, using pseudocode or a flowchart, which:
• inputs the two prices for all 1000 items
• outputs how many items were more expensive in supermarket 1
• outputs how many items were more expensive in supermarket 2
• outputs the largest price difference

Unit 7- Practical problem solving – pseudocode 110 | P a g e


Unit-8:
Programming concepts
Notes for O Level Computer Science 2210 By Farhan Rahmat

Programming Language:

Computers can do such a wide variety of things because they can be programmed. This
means that computers are not designed to do just one job, but to do any job that their
programs tell them to do. A program is a set of instructions that a computer follows to
perform a task.

Programming languages can be used to create programs that control the behavior of a
computer and serve any purpose. Computer languages have some form of written
specification of their Syntax (Rules) and Semantic (Words, phrase & sentences). To write a
well-structured program, a programmer requires a programming language to support the
following „program construct‟:

Sequence: Execution of the program usually following the order in which the steps are
written.

Selection: a decision between alternative routes through the program that involves at least
one condition.

Repetition: a step or sequence of steps repeated within the program as an iteration or


loop.

Subroutine: a sub-program such as a procedure or function that can be started or „called;


by a program instruction and can return control to the next instruction after the calling
instruction on completion of its processing.

Computer programming languages can be divided into two types: low-level, closer to
machine language and high-level, closer to human language such English..

Low Level Language

Machine language:

Machine language has the lowest level of language, because the long string of zeros and
ones in machine code is so difficult for a programmer to read or write. Each complete
machine language instruction consists of an operand code (known as „opcode‟).
Following is the example of opcode:

110000

Some opcodes require one or more operands, which are numerical values or memory
addresses upon which they operate. The operand follows the opcode in the program, for
example:

110000 01011010

Machine code can be represented in a slightly more programmer-friendly format where


each group of four bits (half a byte or a „nibble‟) is coded as one hexadecimal (base-16)
digit. For example the operand 01011010 can be split into two nibbles:0101 and 1010. In
hexadecimal 0101 is 5 and 1010 is A, so the operand can written as 5A. Although this is
easier to read than binary, it is not at all clear to the reader what it means, as the following
fragment of machine code shows:
:100000006E28000000000090025088A018200710
:10001000060343134323423433346134343434353436344A

Unit 8- Programming concepts 110 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Assembly Language:

Computers can only execute programs that are written in machine language. A program
can have thousands or even millions of binary instructions, and writing such a program
would be very tedious and time consuming. Programming in machine language would
also be very difficult because putting a 0 or a 1 in the wrong place will cause an error.

Although a computer‟s CPU only understands machine language, it is impractical for


peopleto write programs in machine language. For this reason, assembly language was
created in the early days of computing as an alternative to machine language. Instead of
using binary numbersfor instructions, assembly language uses short words that are known as
mnemonics. Forexample, in assembly language, the mnemonic add typically means to
add numbers, multypicallymeans to multiply numbers, and movtypically means to move a
value to a location inmemory. When a programmer uses assembly language to write a
program, he or she can writeshort mnemonics instead of binary numbers.

Assembly language programs cannot be executed by the CPU. The CPU onlyunderstands
machine language, so a special program known as an assembler is used totranslate an
assembly language program to a machine language program. This process isshown in
Figure 1-18. The assembly code input to the assembler is known as source code. The
machine language program that is created by the assembler can then be executed by
the CPU is known as object code.

Advantages:

 It is easier to understand as compared to machine language.


 Programmer has complete freedom of choice of instructions and direct control over
the processors communication with its input, output and storage devices.
Disadvantage:

 Lack of relation to a human language makes it difficult for a programmer to read.


 Machine oriented nature makes it harder for a programmer to learn.
 Since it is machine dependent therefore programs are not transferable or portable
and programmer should have the knowledge of the hardware as well.

High Level Language

Although assembly language makes it unnecessary to write binary machine language


instructions, it is not without difficulties. Assembly language is primarily a direct substitute
for machine language, and like machine language, it requires that you know a lot about
theCPU. Assembly language also requires that you write a large number of instructions
foreven the simplest program. Because assembly language is so close in nature to machine
language,it is referred to as a low-level language.

Unit 8- Programming concepts 111 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

In the 1950s, a new generation of programming languages known as high-level


languagesbegan to appear. A high-level language allows you to create powerful and
complex programswithout knowing how the CPU works, and without writing large numbers
of low-levelinstructions. In addition, most high-level languages use words that are easy to
understand.

In Python you would display the message Hello world with the following instruction:
print 'Hello world'

Doing the same thing in assembly language would require several instructions, and an
intimateknowledge of how the CPU interacts with the computer‟s output device. As you
can see from thisexample, high-level languages allow programmers to concentrate on the
tasks they want to performwith their programs rather than the details of how the CPU will
execute those programs.

Since the 1950s, thousands of high-level languages have been created. Table 1-1 lists
severalof the more well-known languages.
High level language use interpreter, compiler or translator to convert human
understandable program to computer readable code (machine code).

Examples:

Many high level languages have appeared since Fortran II the most widely used have
been:

COBOL Business applications

FORTRAN Engg& Scientific Applications

PASCAL General use and as a teaching tool

C & C++ General Purpose - currently most popular.

PROLOG Artificial Intelligence

JAVA General all purpose programming

.NET General or web applications.

Advantages of High level language over low level language:

• The main advantage of high-level languages over low-level languages is that they
are easier to read, write and maintain.

• High-level languages make complex programming simpler.

• High level programming techniques are applicable everywhere even where


computational resources are limited.

• Error ratio is less in high level language and


debugging (locate and correct errors in program code ) is easier.

• Length of the program is also small compared with low level.

• Many real time problems can be easily solved with high level language.

Unit 8- Programming concepts 112 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Comparison of high-level and low-level languages:

High-level language Low-level language

Program instructions are machine-


Program statements are problem-oriented.
oriented.

One assembly language instruction


One statement translates to many
translates to one machine code
machine code instructions.
instruction.

Programs are portable to different types of Programs are not portable to different
computer. types of computer.

Programs must be translated to run on a


Machine language needs no translation.
processor.

Translation to machine language is Translation from assembly to machine


relatively complex. language is relatively simple.

Programs are relatively easy to read and Programs are relatively hard to read and
write. write.

Programs are relatively easy to test, debug Programs are relatively hard to test, debug
and maintain. and maintain.

Interpreter

An interpreter is a program that directly executes code of high level programming


language. Interpreter can convert a source code, usually on a step-by-step, line-by-line
and unit-by-unit basis into machine code.

Interpreted languages are read and then executed directly, with no compilation stage.

Compiler

Compiler is a program that compiles source code into executableinstructions that a


computer can understand, it compiles code and produce an EXE format before it run.

There are two stages of compilation:

Intermediate Compilation

Intermediate level compiles code in the form of Byte code and saves for later
execution without the need to re-read the source file.

Machine code Compilation

Machine code compiles source code directly into machine code using Virtual
machines that execute code directly into machine code

Assembler

Assembler normally converts assembly language‟s source code into machine language.

Unit 8- Programming concepts 113 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Assembly language is a family of low-level languages for programming computers. It


implements a symbolic representation of code.

An assembler is a program that takes basic computer instructions and converts them into a
pattern of bits ( 0& 1) that the computer runs to produce result.

Compression of translation programs

Assembler Compiler Interpreter

Translate processor-specific Translate high-level code Translate high-level


assembly code into into machine code for a language statement and
machine code for specific specific processor and executes them on a
processor. operating system. specific processor and
operating system.

Translates an entire Translate an entire program Translates and executes a


program but does not run but does not run it. program on the target
it. processor, usually one
statement at a time, but
does not create machine
code.

Translates one source code Translates one source code Executes one source code
instruction to one machine statement to one or more statement as one or more
code instruction. machine code instructions. instructions.

Unit 8- Programming concepts 114 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

COMPUTER LANGUAGES

In all over the world, language is the source of communication among human beings.
Different countries/regions have different languages. Similarly, in order to communicate
with the computer user also needs to have a language that should be understood by the
computer. For this purpose, different languages are developed for performing different
types of work on the computer. Basically, languages are divided into two categories
according to their interpretation.

1. Low Level Languages.

2. High Level Languages.

Low Level Languages


Low level computer languages are machine codes or close to it. Computer cannot
understand instructions given in high level languages or in English. It can only understand
and execute instructions given in the form of machine language i.e. language of 0 and 1.
There are two types of low level languages:
 Machine Language.

 Assembly Language
Machine Language: It is the lowest and most elementary level of Programming language
and was the first type of programming language to be developed. Machine Language is
basically the only language which computer can understand. In fact, a manufacturer
designs a computer to obey just one Language, its machine code, which is represented
inside the computer by a String of binary digits (bits) 0 and 1. The symbol 0 stands for the
absence of Electric pulse and 1 for the presence of an electric pulse . Since a computer is
Capable of recognizing electric signals, therefore, it understand machine Language.

Advantages of Machine Language

i) It makes fast and efficient use of the computer.

ii) It requires no translator to translate the code i.e. directly understood by the computer

Disadvantages of Machine Language:

i) All operation codes have to be remembered

ii) All memory addresses have to be remembered.

iii) It is hard to amend or find errors in a program written in the machine language

iv) These languages are machine dependent i.e. a particular machine language can be
used on only one type of computer

Assembly Language

It was developed to overcome some of the many inconveniences of machine language.


This is another low level but a very important language in which operation codes and
operands are given in the form of alphanumeric symbols instead of 0’s and l’s. These
alphanumeric symbols will be known as mnemonic codes and can have maximum up to 5
letter combination e.g. ADD for addition, SUB for subtraction, START,LABEL etc. Because of
this feature it is also known as ‘Symbolic Programming Language’. This language is also very

Unit 8- Programming concepts 115 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

difficult and needs a lot of practice to master it because very small English support is given
to this language. The language mainly helps in compiler orientations. The instructions of the
Assembly language will also be converted to machine codes by language translator to be
executed by the computer.

Advantages of Assembly Language

i) It is easier to understand and use as compared to machine language.

ii)It is easy to locate and correct errors.

iii) It is modified easily

Disadvantages of Assembly Language

i) Like machine language it is also machine dependent.

ii) Since it is machine dependent therefore programmer should have the knowledge of the
hardware also.

High Level Languages

High level computer languages give formats close to English language and the purpose of
developing high level languages is to enable people to write programs easily and in their
own native language environment (English). High-level languages are basically symbolic
languages that use English words and/or mathematical symbols rather than mnemonic
codes. Each instruction in the high level language is translated into many machine
language instructions thus showing one-to-many translation

Types of High Level Languages

Many languages have been developed for achieving different variety of tasks, some are
fairly specialized others are quite general purpose.

These are categorized according to their use as

a) Algebraic Formula-Type Processing. These languages are oriented towards the


computational procedures for solving mathematical and statistical problem

Examples are

 BASIC (Beginners All Purpose Symbolic Instruction Code).


 FORTRAN (Formula Translation).
 PL/I (Programming Language, Version 1).
 ALGOL (Algorithmic Language).
 APL (A Programming Language).
b) Business Data Processing:

 These languages emphasize their capabilities for maintaining data processing


procedures and files handling problems. Examples are:
 COBOL (Common Business Oriented Language).
 RPG (Report Program Generator

Unit 8- Programming concepts 116 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

b) String and List Processing: These are used for string manipulation including search for
patterns, inserting and deleting characters. Examples are:

 LISP (List Processing).


 Prolog (Program in Logic).
Object Oriented Programming Language

In OOP, the computer program is divided into objects. Examples are:

 C++
 Java
e) Visual programming language: these are designed for building Windows-based
applications Examples are:

 Visual Basic
 Visual Java
 Visual C

Advantages of High Level Language

Following are the advantages of a high level language:

 User-friendly
 Similar to English with vocabulary of words and symbols
 Therefore it is easier to learn.
 They require less time to write.
 They are easier to maintain.
 Problem oriented rather than 'machine' based.
 Program written in a high-level language can be translated into many machine
language and therefore can run on any computer for which there exists an
appropriate translator.
 It is independent of the machine on which it is used i.e. Programs developed in high
level language can be run on any Computer

Unit 8- Programming concepts 117 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Disadvantages of High Level Language

 A high-level language has to be translated into the machine language by a translator


and thus a price in computer time is paid.
 The object code generated by a translator might be inefficient Compared to an
equivalent assembly language program
 Types of computer languages
As we human beings communicate with each other’s in different language such as
Urdu, French, Punjabi and Arabic etc. Similarly to communicate with the computers we
have to use specific languages and for this..

Unit 8- Programming concepts 118 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Language Generations

Computer languages have the same history as the computer itself history.

There are five generations of languages when programming method and techniques
could bedeveloped as far as development in hardware occurred.

First Generation (1GL)

First-generation language was machine language or the level of instructions and data that
the processor is actually given to work on binary numbers 0s and 1s.

First-generation language is the lowest level computer language. Information is conveyed


to the computer by the programmer as binary instructions.

In the 1940s and 1950s, computers were programmed by scientists sitting before control
panels equipped with switches so that they could input instructions as strings of zeros and
ones.

Second Generation (2GL)

Second-generation language used assembly language, An assembler converts the


assembler language statements into machine language.

By the late 1950s, this language had become popular. Assembly language consists of
letters of the alphabet.

This makes programming much easier than trying to program a series of zeros and ones.

Second-generation language use increased when Grace Hopper developed FLOW-


MATIC, a language that made programming easier.

Third Generation (3GL)

Third-generation language is a high-level programming language, such as PL/I, COBOL,


FORTRAN and C.

Compiler based FORTRAN and COBOL created because it improved the record keeping
and data management ability in many business applications.

In the early 1960s, BASIC language designed and used bynonprofessional programmers.
BASIC remained popular during the 1970s and 1980s.

Programs written in third-generation languages require more memory and run more slowly
than those written in lower level languages.

Fourth Generation (4GL)

Fourth-generation language is designed to be closer to natural language than a 3GL


language. Fourth-generation languages attempt to make communicating with computers
as much like the processes of thinking and talking to other people as possible. Fourth-
generation languages typically consist of English-like words and phrases, some of these
languages include graphic devices such as icons and onscreen push buttons for use during
programming and when running the application.

Unit 8- Programming concepts 119 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Many fourth-generation languages use C, C++, Java and SQL that support stand-alone as
well as web applications.

Fifth Generation (5GL)

Fifth-generation language is programming that uses a visual or graphical development


interface to create source language that is usually compiled with a 3GL or 4GL language
compiler.

Microsoft, Borland, IBM, and other companies make 5GL visual programming products for
developing applications in Java, J++, Visual Java, Visual Basic, ASP, ASP.NET, VB.NET and
C#.

Visual programming allows you to see object oriented structures and drag icons to
assemble program blocks.

Unit 8- Programming concepts 120 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Data types and data structures

Define and use different data types e.g. integer, real, boolean, character and string

A data type is a method of interpreting a pattern of bits.

Intrinsic data types

Intrinsic data types are the data types that are defined within a particular programming
language.

There are numerous different data types. They are used to make the storage and
processing of data easier and more efficient. Different databases and programming
systems have their own set of intrinsic data types, but the main ones are:

• Integer;
• Real;
• Boolean;
• String;
• Character;
• Date;
• Container.
Integer
An integer is a positive or negative number (-32,768 to 32,767) that does not contain a
fractional part. Integers are held in pure binary for processing and storage. Note that some
programming languages differentiate between short and long integers (more bytes being
used to store long integers).
Real
A real is a number that contains a decimal point. In many systems, real numbers are
referred to as singles and doubles, depending upon the number of bytes in which they are
stored.
Boolean
A Boolean is a data-type that can store one of only two values – usually these values are
True or False. Booleans are stored in one byte – True being stored as 11111111 and False as
00000000.
String
A string is a series of alphanumeric characters enclosed in quotation marks. A string is
sometimes just referred to as „text‟. Any type of alphabetic or numeric data can be stored
as a string: “Birmingham City”, “3/10/03” and “36.85” are all examples of strings. Each
character within a string will be stored in one byte using its ASCII code; modern systems
might store each character in two bytes using its Unicode. The maximum length of a string is
limited only by the available memory.

Notes:
• if dates or numbers are stored as strings then they will not be sorted correctly; they
will be sorted according to the ASCII codes of the characters – “23” will be placed
before “9”;
• telephone numbers must be stored as strings or the leading zero will be lost.

Unit 8- Programming concepts 121 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Character

A character is any letter, number, punctuation mark or space, which takes up a single unit
of storage (usually a byte). In some programming languages it is written as Char.

Dates

In most computer systems dates are stored as a „serial‟ number that equates to the number
of seconds since January 1st, 1904 (thus they also contain the time). Although the serial
numbers are used for processing purposes, the results are usually presented in one of
several „standard‟ date formats – for example, dd/mm/yyyy, or ddMonthName, yyyy.
Dates usually take 8 bytes of storage.

Comparison of the common data types:

Unit 8- Programming concepts 122 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Variables:

• Hold data in memory


• Are assigned a data type
• The data can change throughout the program‟s operation
• The data entered must be the same data type as assigned to the variable

Variables are a name that is given to the data. The name must not start with a number or
character that is not a letter. Also, the name of the variable must not be a reserved name
like PRINT, INPUT, LET, ABS, BEEP, etc.

DIM is used to make variables of a data type.

Dim [Variable Name] As Data Type [= initial value]

Dim [Variable Name] As String


Dim [Variable Name] As Integer
Dim [Variable Name] As Long
Dim [Variable Name] As Single
Dim [Variable Name] As Double

Examples:

Dim MyNameAs String


Dim Num1 As Integer
Dim Num2 As Single
Dim Answer As Single

Sample Code:
Module DataTypes
Sub Main()
Dim b As Byte
Dim n As Integer
Dim si As Single
Dim d As Double
Dim da As Date
Dim c As Char
Dim s As String
Dim bl As Boolean
b = 1
n = 1234567
si = 0.12345678901234566
d = 0.12345678901234566
da = Today
c = "U"c
s = "Me"
If ScriptEngine = "VB" Then
bl = True
Else
bl = False
End If
If bl Then
'the oath taking
Console.Write(c &" and," & s &vbCrLf)
Console.WriteLine("declaring on the day of: {0}", da)
Console.WriteLine("We will learn VB.Net seriously")
Console.WriteLine("Lets see what happens to the floating point variables:")
Console.WriteLine("The Single: {0}, The Double: {1}", si, d)
End If
Console.ReadKey()
End Sub

Unit 8- Programming concepts 123 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

End Module

When the above code is compiled and executed, it produces following result:
U and, Me
declaring on the day of: 12/4/2012 12:00:00 PM
We will learn VB.Net seriously
Lets see what happens to the floating point variables:
The Single:0.1234568, The Double: 0.123456789012346

Remember that selecting the right data type for the variable is very important to make the
program run properly.

Unit 8- Programming concepts 124 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Program construct in VB.Net:

1.1 counting
Counting in 1s is quite simple; use of the statement count = count + 1 will enable counting
to be done (e.g. in controlling a repeat loop). The statement literally means: the (new)
count = the (old) count + 1

It is possible to count in any increments just by altering the numerical value in the statement
(e.g. count = count – 1 counts backwards)
Public Class Test
Public Shared Sub Main()
DIM Weather as String
DIM Foggy as Integer=0
DIM Cloudy as Integer=0
DIM Rainy as Integer=0
DIM Sunny as Integer=0
Weather=Console.ReadLine()
Select Weather
Case "Foggy"
Foggy=Foggy+1
Case "Cloudy"
Cloudy=Cloudy+1
Case "Rainy"
Rainy=Rainy+1
CaseElse
Sunny=Sunny+1
End Select
Console.WriteLine (Foggy)
Console.WriteLine (Cloudy)
Console.WriteLine (Rainy)
Console.WriteLine (Sunny)
End Sub
End Class

1.2 totalling
To add up a series numbers the following type of statement should be used:

total= total + number


This literally means (new) total = (old) total + value of number
| Dimsum As Integer= 0
| Dim count As Integer= 0
| For count=1 To 10
| Console.WriteLine ("enter a number")
| n=Console.ReadLine()
| sum = sum + n
| Next
| Console.WriteLine("The sum of the numbers you gave is"&sum)

1.3 input/output

Input and output indicated by the use of the commandConsole.ReadLine()


&Console.WriteLine()

Example:

Print “Hello World” till code 9999 was entered:

Module Module1
Sub Main()
DimCodeAs Integer=0

Unit 8- Programming concepts 125 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Code=Console.ReadLine()
WhileCode<>9999
Console.WriteLine(“Hello World”)
Code=Console.ReadLine()
End While
End Sub
End Module

1.4 branching

Selection
Selection is a control structure in which there is a test to decide if certain instructions are
executed.
IF-THEN-ELSE
This selection method is used if there are two possible outcomes to a test:
The syntax of an If...Then... Else statement in VB.Net is as follows:

If(boolean_expression)Then
'statement(s) will execute if the Boolean expression is true
Else
'statement(s) will execute if the Boolean expression is false
EndIf

If the Boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.

Example:

Dim count As Integer = 0


Dim message As String

If count = 0 Then
message = "There are no items."
ElseIf count = 1 Then
message = "There is 1 item."
Else
message = "There are " & count & " items."
End If

SELECT-CASE

This selection method is used if there are more than two possible outcomes to a test:

Creating a Select-Case statement is simple to do. The next program will prompt the user to
select the key A-D and the program will respond by telling the user what key was entered.
We will create a Select-Case statement for the A-D keys entered.
Dim KeyPressedAs String
Console.WriteLine("Please Enter A Key (A,B,C,D): ")
KeyPressed=Console.ReadLine()
Select KeyPressed
Case "A"
Console.WriteLine("A Was Entered")
Case "B"
Console.WriteLine("B Was Entered")

Unit 8- Programming concepts 126 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Case "C"
Console.WriteLine("C Was Entered")
Case "D"
Console.WriteLine("D Was Entered")
Case Else
Console.WriteLine("Some Other Key Was Entered")
End Select

1.5 loops

Iteration
Iteration is a control structure in which a group of statements is executed repeatedly –
either a set number of times, or until a specific condition is True.

FOR-NEXT
This is an unconditional loop in which the number of repetitions is set at the beginning.

The syntax for this loop construct is:


For counter [Asdatatype]= start Toend[Stepstep]
[ statements]
[ ContinueFor]
[ statements]
[ExitFor]
[ statements]
Next[ counter]

Sample code:

Print “Hello World” 100 times:


ModuleModule1
Sub Main()
DimCountAsInteger
ForCount= 1 To100
Console.WriteLine("Hello World”)
Next
End Sub
End Module

WHILE-ENDWHILE

It executes a series of statements as long as a given condition is True.

The syntax for this loop construct is:

While condition
[ statements]
[ ContinueWhile]
[ statements]
[ExitWhile]
[ statements]
EndWhile

Here, statement(s) may be a single statement or a block of statements. The condition may
be any expression, and true is logical true. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately
following the loop.

Unit 8- Programming concepts 127 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Sample code:

Print “Hello World” till code 9999 was entered:

Module Module1
Sub Main()
DimCodeAs Integer=0
Code=Console.ReadLine()
WhileCode<>9999
Console.WriteLine(“Hello World”)
Code=Console.ReadLine()
End While
End Sub
End Module

REPEAT-UNTIL
This is a conditional loop, which has a test at the end and repeats until the condition is true:

Do
[ statements]
[ ContinueDo]
[ statements]
[ExitDo]
[ statements]
LoopUntil condition

Sample Code:
Module loops
SubMain()
' local variable definition
Dim a AsInteger=10
'do loop execution
Do
Console.WriteLine("value of a: {0}", a)
a = a +1
LoopUntil(a =20)
Console.ReadLine()
EndSub
EndModule

When the above code is compiled and executed, it produces the following result:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Unit 8- Programming concepts 128 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

The structure of procedural programs

Statement, subroutine, procedure, function, parameter, loop

Procedural programs are ones in which instructions are executed in the order defined by
the programmer.

Procedural languages are often referred to as third generation languages and include
FORTRAN, ALGOL, COBOL, BASIC, and PASCAL.

Statement
A statement is a single instruction in a program, which can be converted into machine
code and executed.

In most languages a statement is written on a single line, but some languages allow
multiple lines for single statements.

Examples of statements are:

DIM name As String


A=X*X
While x < 10

Subroutine
A subroutine is a self-contained section of program code that performs a specific task, as
part of the main program.

Procedure
A procedure is a subroutine that performs a specific task without returning a value to the
part of the program from which it was called.

Function
A function is a subroutine that performs a specific task and returns a value to the part of the
program from which it was called.

Note that a function is „called‟ by writing it on the right hand side of an assignment
statement.

Parameter
A parameter is a value that is „received‟ in a subroutine (procedure or function).

The subroutine uses the value of the parameter within its execution. The action of the
subroutine will be different depending upon the parameters that it is passed.

Parameters are placed in parenthesis after the subroutine name. For example:
Square(5) „passes the parameter 5 – returns 25
Square(8) „passes the parameter 8 – returns 64
Square(x) „passes the value of the variable x

Unit 8- Programming concepts 129 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Understand, create and use subroutines (procedures and functions), including the passing
of parameters and the appropriate use of the return value of functions

Use subroutines to modularize the solution to a problem

Subroutine/sub-program
A subroutine is a self-contained section of program code which performs a specific task
and is referenced by a name.

A subroutine resembles a standard program in that it will contain its own local variables,
data types, labels and constant declarations.

There are two types of subroutine. These are procedures and functions.

• procedures are subroutines that input, output or manipulate data in some way;
• functions are subroutines that return a value to the main program.

A subroutine is executed whenever its name is encountered in the executable part of the
main program. The execution of a subroutine by referencing its name in the main program
is termed „calling‟ the subroutine.

The advantages of subroutines.

The advantage of using procedures and functions are that:

• the same lines of code are re-used whenever they are needed – they do not have
to be repeated in different sections of the program.
• a procedure or function can be tested/improved/rewritten independently of other
procedures or functions.
• it is easy to share procedures and functions with other programs – they can be
incorporated into library files which are then „linked‟ to the main program;
• a programmer can create their own routines that can be called in the same way as
any built-in command.

Defining Sub Procedures

The Sub statement is used to declare the name, parameter and the body of a
subprocedure. The syntax for the Substatement is:

Where,

 Modifiers: specify the access level of the procedure; possible values are: Public,
Private, Protected, Friend,Protected Friend and information regarding overloading,
overriding, sharing, and shadowing.
 SubName: indicates the name of the Sub
 ParameterList: specifies the list of the parameters

Unit 8- Programming concepts 130 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Example

The following example demonstrates a Sub procedure CalculatePaythat takes two


parameters hours and wages anddisplays the total pay of an employee:

When the above code is compiled and executed, it produces following result:

Passing Parameters by Value

This is the default mechanism for passing parameters to a method. In this mechanism, when
a method is called, a newstorage location is created for each value parameter. The values
of the actual parameters are copied into them. So, thechanges made to the parameter
inside the method have no effect on the argument.

In VB.Net, you declare the reference parameters using the ByValkeyword. The following
example demonstrates the
concept:

When the above code is compiled and executed, it produces following result:

Unit 8- Programming concepts 131 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

It shows that there is no change in the values though they had been changed inside the
function.

Passing Parameters by Reference

A reference parameter is a reference to a memory location of a variable. When you pass


parameters by reference, unlikevalue parameters, a new storage location is not created
for these parameters. The reference parameters represent thesame memory location as
the actual parameters that are supplied to the method.

In VB.Net, you declare the reference parameters using the ByRefkeyword. The following
example demonstrates this:

When the above code is compiled and executed, it produces following result:

All executable code must be inside a procedure. Use a Sub procedure when you don't want to
return a value to the calling code. Use a Function procedure when you want to return a value.

Unit 8- Programming concepts 132 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Defining a Function

The Function statement is used to declare the name, parameter and the body of a function. The
syntax for the Functionstatement is:

Where,
Tutorial content goes here.....
 Modifiers: specifiy the access level of the function; possible values are: Public, Private,
Protected, Friend, Protected Friend and information regarding overloading, overriding,
sharing, and shadowing.
 FunctionName: indicates the name of the function
 ParameterList: specifies the list of the parameters
 ReturnType: specifies the data type of the variable the function returns

Example
Following code snippet shows a function FindMax that takes two integer values and returns the
larger of the two.

Function Returning a Value

In VB.Net a function can return a value to the calling code in two ways:
 By using the return statement
 By assigning the value to the function name
The following example demonstrates using the FindMax function:

When the above code is compiled and executed, it produces following result:

Unit 8- Programming concepts 133 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Define and use arrays (one- and two-dimensional) for solving simple problems (this should
include initialising arrays, reading data into arrays and performing a simple serial search on
a one-dimensional array)

A data structure is a collection of different data items that are stored together in a clearly
defined way. Two common data structures are arrays and records.

Array

An array is a data structure, which allows a set of items of identical data type to be stored
together using the same identifier name.

Arrays are declared in a similar way to standard variables, except that the array size and
dimensions are included. For example, the following declares an array that reserves five
locations in memory and labels these as „Names‟:

DIM Names(4) As String

The five individual locations are Names(0), Names(1), Names(2), Names(3), Names(4).

Each data item is called an element of the array. To reference a particular element a
programmermust use the appropriate index. For example, the following statement assigns
data to the 5thelement:

Names(4) = “John”

Arrays simplify the processing of similar data. An algorithm for getting five names from the
user and storing them in the array Names is shown below:

Dim Names(4) As String


For i=0 to 4
Input Value
Names(i)=Value
Next i

One-dimensional arrays
A one-dimensional array is a data structure in which the array is declared using a single
index and can be visually represented as a list.

The following diagram shows the visual representation of the array Names(4):

Unit 8- Programming concepts 134 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Write and test a program to complete the three tasks.


TASK 1
Input and store the names and marks for 30 students who have sat three computer science
tests.
Test 1 is out of 20 marks, Test 2 is out of 25 marks, Test 3 is out of 35 marks. You must store
thenames in a one-dimensional array and the marks and total score for each student in
one-dimensionalarrays. All the marks must be validated on entry and any invalid marks
rejected. You may assumethat the students‟ names are unique.

TASK 2
Calculate and store the total score for each student and calculate the average score for
the wholeclass. Output each student‟s name followed by their total score, then output the
average score for theclass.

TASK 3
Select the student with the highest score and output their name and score.
Your program must include appropriate prompts for the entry of data. Error messages and
otheroutput need to be set out clearly and understandably. All variables, constants and
other identifiersmust have meaningful names. Each task must be fully tested.

Unit 8- Programming concepts 135 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Convert following pseudocode into programs using any high level language:
The following five examples use the above pseudocode terms. These are the same
problems discussed in section 3.1 using flow charts – both methods are acceptable ways of
representing an algorithm.

2.1 Example 1
A town contains 5000 houses. Each house owner must pay tax based on the value of the
house. Houses over $200 000 pay 2% of their value in tax, houses over $100 000 pay 1.5% of
their value in tax and houses over $50 000 pay 1% of their value in tax. All others pay no tax.
Write an algorithm to solve the problem using pseudocode.

forcount  1 to 5000
inputhouse
ifhouse > 50 000 then tax  house * 0.01
else if house > 100 000 then tax  house * 0.015
else if house > 200 000 then tax  house * 0.02
elsetax  0
printtax
next

For example,
count 0
whilecount < 5001
inputhouse
ifhouse > 50000 then tax  house * 0.01
else if house > 100 000 then tax  house * 0.015
else if house > 200 000 then tax  house * 0.02
elsetax  0
endif
endif
endif
printtax
count = count + 1
endwhile

EXERCISE: Re-write the above algorithm using a repeat loop and modify the if … then …
else statements to include both parts of the house price range.
(e.g. if house > 50000 and house <= 100000 then tax = house * 0.01)

Unit 8- Programming concepts 136 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

2.2 Example 2
The following formula is used to calculate n: n = x * x/(1 – x)
The value x = 0 is used to stop the algorithm. The calculation is repeated using values of x
until the value x = 0 is input. There is also a need to check for error conditions. The values of
n and x should be output.

Write an algorithm to show this repeated calculation using pseudocode.


NOTE: It is much easier in this example to input x first and then loop round doing the
calculation until eventually x = 0. Because of this, it would be necessary to input x twice (i.e.
inside the loop and outside the loop). If input x occurred only once it would lead to a more
complicated algorithm.

(Also note in the algorithm that <> is used to represent ≠ ).


A while loop is used here, but a repeat loop would work just as well.

inputx
whilex <> 0 do
ifx = 1 then print “error”
elsen = (x * x)/(1 – x)
printn, x
endif
inputx
endwhile

2.3 Example 3
Write an algorithm using pseudocode which takes temperatures input over a 100 day
period (once per day) and output the number of days when the temperature was below
20C and the number of days when the temperature was 20C or above.

(NOTE: since the number of inputs is known, a for … to loop can be used. However, a while
loop or a repeat loop would work just as well).
total1 = 0: total2 = 0
fordays = 1 to 100
inputtemperature
iftemperature < 20 then total1 = total1 + 1
elsetotal2 = total2 + 1
endif
next
printtotal1, total2

This is a good example of an algorithm that could be written using the case construct
rather than if … then … else. The following section of code replaces the statements if
temperature < 20 then …… endif:
casetemperature of
1: total1 = total1 + 1
2: total2 = total2 + 1
endcase

Unit 8- Programming concepts 137 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

2.4 Example 4
Write an algorithm using pseudocode which:

 inputs the top speeds of 5000 cars


 outputs the fastest speed and the slowest speed
 outputs the average speed of all the 5000 cars

(NOTE: Again since the actual number of data items to be input is known any one of the
three loop structures could be used. It is necessary to set values for the fastest (usually set at
zero) and the slowest (usually set at an unusually high value) so that each input can be
compared. Every time a value is input which > the value stored in fastest then this input
value replaces the existing value in fastest; and similarly for slowest).

fastest = 0: count = 0
slowest = 1000
repeat
inputtop_speed
total = total + top_speed
iftop_speed> fastest then fastest = top_speed
iftop_speed< slowest then slowest = top_speed
endif
endif
count + count + 1
untilcount = 5000
average = total * 100/5000
printfastest, slowest, average

Unit 8- Programming concepts 138 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

2.5 Example 5
A shop sells books, maps and magazines. Each item is identified by a unique 4 – digit code.
All books have a code starting with a 1, all maps have a code starting with a 2 and all
magazines have a code beginning with a 3. The code 9999 is used to end the program.

Write an algorithm using pseudocode which input the codes for all items in stock and
outputs the number of books, maps and magazine in stock. Include any validation checks
necessary.

(NOTE: A 4-digit code implies all books have a code lying between 1000 and 1999, all maps
have a code lying between 2000 and 2999 and all magazines a code lying between 3000
and 3999. Anything outside this range is an error)

books = 0: maps = 0: mags = 0


repeat
inputcode
ifcode > 999 and code < 2000 then books = books + 1
else if code > 1999 and code < 3000 then maps = maps + 1
else if code > 2999 and code < 4000 then mags = mags + 1
else print “error in input”
endif:endif:endif
untilcode = 9999
printbooks, maps, mags

(NOTE: A function called INT(X) is useful in questions like this. This returns the integer (whole
number) part of X e.g. if X = 1.657 then INT(X) = 1; if X = 6.014 then INT(X) = 6 etc. Using this
function allows us to use the case statement to answer this question:

books = 0: maps = 0: mags = 0


repeat
inputcode
x = INT(code/1000) * divides code by 1000 to give a
casex of * number between 0 and 9
1: books = books + 1
2: maps = maps + 1
3: mags = mags + 1
otherwise print “error”
endcase
untilcode = 9999
printbooks, maps, mags

this is probably a more elegant but more complex solution to the problem)

Unit 8- Programming concepts 139 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Past Paper Questions:

May/June 2006 P1
a) Give two benefits of using a high-level language for writing programs. [2]
(b) State one type of program that would be written in a low-level language rather than
ahigh-level language and give a reason why. [2]

Oct/Nov 2006 P1
10 A robot arm is to be used to move some objects which are positioned on the grid shown.
Object “X” is located at A7 and is to be moved to F7. Object “Y” is located at C6 and is to
bemoved to G5.

The START position for the robot arm is shown. The robot arm can travel left and right
alongthe top of the grid, and the robot arm can extend (lengthen) and retract (shorten) so
that thegripper at the end of the arm can reach any grid square.

The following commands must be used:

For example, to move block “X” from square A7 to F7 (beginning at START) would require
the following instructions:
Left 8
Down 6
Close
Up 6
Right 5
Down 6
Open

Unit 8- Programming concepts 140 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Write a set of instructions to transfer block “Y” from C6 to G5 (beginning at START). [3]

Oct/Nov 2007 P1

Give two differences between high level languages and low level languages.

May/June 2008 P1

7 A floor turtle can use the following instructions:

Unit 8- Programming concepts 141 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2008 P1

3 Write a routine using a for … to loop which inputs 100 numbers and outputs how many of
the numbers were negative. [3]

Oct/Nov 2009 P1

Give two advantages of using high level languages when writing new computer
softwarerather than using low level languages

May/June 2010 P11

10 (a) Compilers and interpreters translate high-level languages. Give two differences
between compilers and interpreters.
(b) Programs can be written using high-level or low-level languages.
Give one advantage of using each method.
High-level language advantage
Low-level language advantage
(c) What is meant by top-down design when developing new software?

Unit 8- Programming concepts 142 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2010 P12


15 A floor turtle can use the following instructions:

(In the following grid, each square is 10 cm by 10 cm.)

Unit 8- Programming concepts 143 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2011 P12

1h=0
2c=0
3 REPEAT
4 READ x
5 IF x > h THEN x = h
6c=c+1
7 PRINT h
8 UNTIL c < 20
The above code is an example of a high-level language.

Unit 8- Programming concepts 144 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Give TWO features of a high-level language. [2]


(c) The code is to be interpreted rather than compiled.
Give ONE difference between these two methods. [1]

May/June 2012 P11

5 A floor turtle can use the following instructions.

Unit 8- Programming concepts 145 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2012 P12

Look at these two pieces of code:

(a) Which of these pieces of code is written in a high-level language? [1]


(b) Give one benefit of writing code in a high-level language. [1]
(c) Give one benefit of writing code in a low-level language. [1]
(d) High-level languages can be compiled or interpreted.
Give two differences between a compiler and an interpreter.

Unit 8- Programming concepts 146 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2014 P11

5 A floor turtle can use the following instructions.

Unit 8- Programming concepts 147 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2014 P12

7 A floor turtle uses the following commands:

In the following grid, each of the squares measures 10 cm by 10 cm:

Complete the set of instructions to draw the shape shown above (in bold lines).

Unit 8- Programming concepts 148 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2014 P12

9 A floor turtle uses the following commands:

Unit 8- Programming concepts 149 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 8- Programming concepts 150 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Unit 8- Programming concepts 151 | P a g e


Unit-9:
Databases
Notes for O Level Computer Science 2210 By Farhan Rahmat

Databases:

A database is a way of storing information in a structured, logical way. Databases are used
to collect and organise information such as customer details for a business, medical
records at a surgery and stock items in a warehouse.

Database content is easy to manage. Information can be accessed and updated quickly
and efficiently. A database can store and handle vast amounts of data. A user can sort
and search a database to find any requested data.
Most databases have the following properties:

Tables

Data is stored in rows and columns (much like a spreadsheet – the main difference is how
the data is organised). Each row in a table is called a record which is made up of a
number of fields (columns in the table). The data type in the fields is usually either text,
numeric or date/time. Most databases contain a number of tables which are usually linked
together in some way.

Record
A record is a collection of fields that contains data about a single item or person – it is a
row within a table.

Field

A field is a single category of data within a database, which appears in all the records of a
table – it is a column within a table.

Key fields

A key field is used to identify the records within a database. There are two types of keys:
• primary key;
• secondary key.

Primary key
The Primary key is a unique field that identifies a single record. This prevents any records
from having the same value.
Some „natural‟ primary keys are:
• CarRegistrationNumber;
• ISBN – a 10-digit code that uniquely identifies a book;
• MAC number – a 6-part number that uniquely identifies a network card
• NationalInsuranceNumber – can uniquely identify employees of a company (not
usable for under 16s or for non-British nationalists!)

Secondary key
A Secondary key is a non-unique field, used in a search, that does not always produce
only one matching record.
Some typical secondary keys are:
• LastName;
• PostCode;
• DateOfBirth

Unit 9- Databases 151 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

The following terms are used to describe parts of a database:


Ke
y
Fie
ld

Record structure

Before setting up a database, the record structure must be decided to make best use of
the memory and backing store, and to make searching and report creation easier.
For example, a car showroom wants to record details of the cars it sells. Before setting up
the database, the following attributes need to be decided:
Field Name, Field type, Field size, Format, Input Mask, Validation Rule

Record structure

Field name Field type Format

Registration number Alphanumeric Up to 7 characters - the key field

Make Alphanumeric Up to 15 characters

Model Alphanumeric Up to 15 characters

Date first registered Date DDMMYY

Price Currency Up to 5 numbers

Taxed Yes/No (Boolean) 1 character Y/N

...

When designing a database it is important to choose the correct field type. This ensures
that the data stored is usable and it makes validation easier. For example, if the price paid
for goods was stored in a text field, then the database wouldn‟t be able to add each
individual figure to produce a total.

Unit 9- Databases 152 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Following is the list of common data types:

Unit 9- Databases 153 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Validation

Validation checks ensure that data entered into the computer is sensible. Data is checked
in accordance with a set of rules. The computer's software can validate data while it is
being entered into the computer. The main purpose of data validation is to spot an error.
This can be done quickly and easily as the process is automated.

1. Range check. A mathematics exam is out of 100. A simple validation rule that the
computer can apply to any data that is input is that the mark must be between 0 and 100
inclusive. Consequently, a mark of 101 would be rejected by this check as being outside
the acceptable range.

2. Character check. A person‟s name will consist of letters of the alphabet and sometimes
a hyphen or apostrophe. This rule can be applied to input of a person‟s name so that
dav2d will immediately be rejected as unacceptable.

3. Format check. A particular application is set up to accept a national insurance number.


Each person has a unique national insurance number, but they all have the same format of
characters, 2 letters followed by 6 digits followed by a single letter. If the computer knows
this rule then it knows what the format of a NI number is and would reject ABC12345Z
because it is in the wrong format, it breaks the rule.

4. Length check. A NI number has 9 characters, if more or fewer than 9 characters are
keyed in then the data cannot be accurate.

5. Existence check. A bar code is read at a supermarket check out till. The code is sent to
the main computer which will search for that code on the stock file. As the stock file
contains details of all items held in stock, if it is not there then the item cannot exist, which it
obviously does, therefore the code must have been wrongly read.

Coding of data:

Any system will need to have data collected, entered and stored.

One method of storing data is to assign codes to it. This usually means shortening the
original data in an agreed manner. The agreement is between the users of the system. This
coding scheme could be part of the training of how to use the system, and it could also be
documented within the system for new users.

If the coding is completely obvious then there is no such need for formaldocumentation.
For example if a field called 'Gender' has only two values 'M' and 'F'. It should be obvious
from the field name that this refers to Male and Female.

Example 1

Original data: Monday; Tuesday; Wednesday; Thursday; Friday

Coded data: Mon; Tues; Wed; Thurs; Fri

Unit 9- Databases 154 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Example 2

Original data: Xtra Large; Large; Medium; Small

Coded data: XL; L; M; S

Pros and cons of coding

Advantages of coding Disadvantages of coding

Data entry can be faster Coarsening of data

Data entry can be more accurate Meaning of data can be obscured

Validation can further improve accuracy Value judgements are difficult to code

If people don't know the code it can slow


Less storage space required
down data entry

If codes are complicated they might be


Faster searching for data
entered incorrectly

Coded data can be more secure if people don't


Might run out of code combinations
know what it means

Unit 9- Databases 155 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Estimate the size of a file from its structure and the number of records

The basic formula for estimating the size of a file is:

If we consider a file with 200 records, which stores the details of an organisation‟s
customers:

CUSTOMER(RefCode, Name, PostCode, Telephone, DoB, Age)

We can estimate the size of the record as follows:

Thus 200 records would require:

Note that to determine the maximum field length, an extreme case was considered and
several bytes added to play safe.

Unit 9- Databases 156 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Database Management System:

We have discussed the structure of a database as consisting of one or more tables, each
of which contain records and fields of various data types.

The next requirement is to have a system in place that can act upon that data as well as
creating and maintaining the database itself.

This is the role of the 'database management system' usually referred to as a DBMS.

A DBMS is an application designed to control all aspects of a database.

The DBMS will have a command language. This includes command statements for:

 Creating an empty database


 Deleting an entire database
 Creating and deleting tables
 Inserting new records into tables
 Updating and deleting records
 Being able to extract data sets
 Being able to produce reports that summarise the data
 Being able to process the data to create new data

There are many database management systems that are either commercial products or
free open source applications.

Examples include
Name Comment

A very popular, free open source system, widely used on web


MySQL
sites

Access Included in some versions of the Microsoft Office suite

Base Part of the free Open Office suite

A multi-user enterprise level database management system.


Oracle
Widely used in industry

Unit 9- Databases 157 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Queries

Queries most commonly allow information to be retrieved from tables. Since the
information is often spread across several tables, queries allow it to be viewed as one single
datasheet. They also allow filtering so only the records required are seen. Queries can be
either results seen directly on the screen or the output to another form or report. Example of
a query: (house > 200 000) OR (no_of_rooms< 4).

Points to note: (1) there are 10 records in this section of the database
(2) each record has 4 fields
(3) sample queries:
(Smallest size (microns) < 1) OR (Toxic = “yes”)
would output records 4, 7, 8 and 9
(Largest size (microns) > 99) AND (Toxic = “no”)
Would output records 1, 2, 3, 6 and 10
The query should match up with the field titles to ensure a correct search is carried out.
Search engines on the Internet work in a similar way; the clever part is how the information
is stored on the databases so that the time to do the search (based on key words) and the
effectiveness of the search itself results in a very powerful and very useful tool.

Unit 9- Databases 158 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

SELECT STATEMENT

The SELECT statement is a SQL query to retrieve records from database.

SELECT SYNTAX

The syntax for the SQL SELECT statement is:

SELECT expressions
FROM tables
WHERE conditions;

expressions are the columns or calculations that you wish to retrieve.

tables are the tables that you wish to retrieve records from. There must be at least one
table listed in the FROM clause.

conditions are conditions that must be met for the records to be selected.

SQL SELECT EXAMPLE - SELECT ALL FIELDS FROM ONE TABLE

Let's look at how to use a SQL SELECT query to select all fields from a table.
SELECT *
FROM suppliers
WHERE city = 'Newark'
ORDER BY city DESC;

In this SQL SELECT statement example, we've used * to signify that we wish to view all fields from
the suppliers table where the supplier resides in Newark. The result set is sorted by city in
descending order.

SQL SELECT EXAMPLE - SELECTING INDIVIDUAL FIELDS FROM ONE TABLE

You can also use the SQL SELECT statement to select individual fields from the table, as opposed
to all fields from the table.

For example:
SELECT supplier_name, city, state
FROM suppliers
WHERE supplier_id> 1000
ORDER BY name ASC, city DESC;

This SQL SELECT example would return only the supplier_name, city, and state fields from
the suppliers table where the supplier_id value is greater than 1000. The results are sorted by
supplier_name in ascending order and then city in descending order.

Unit 9- Databases 159 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

SELECT Column Example

Below is a selection from the "Customers" table:


CustomerID CustomerName ContactName Address City PostalCode Country
1 AlfredsFutterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

4 Around the Horn Thomas 120 Hanover London WA1 1DP UK


Hardy Sq.

5 Berglundssnabbköp Christina Berguvsvägen Luleå S-958 22 Sweden


Berglund 8

SELECT Column Example

The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table:
Example
SELECT CustomerName,City FROM Customers;

SELECT * Example

The following SQL statement selects all the columns from the "Customers" table:
Example
SELECT * FROM Customers;

The SQL WHERE Clause

The WHERE clause is used to extract only those records that fulfill a specified criterion.

SQL WHERE Syntax


SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;

WHERE Clause Example

The following SQL statement selects all the customers from the country "Mexico", in the
"Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Mexico';

Text Fields vs. Numeric Fields

SQL requires single quotes around text values (most database systems will also allow double
quotes).

Unit 9- Databases 160 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

However, numeric fields should not be enclosed in quotes:


Example
SELECT * FROM Customers
WHERE CustomerID=1;

Operators in The WHERE Clause

The following operators can be used in the WHERE clause:


Operator Description
= Equal

<> Not equal. Note: In some versions of SQL this operator may be written as !=

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

BETWEEN Between an inclusive range

LIKE Search for a pattern

IN To specify multiple possible values for a column

The SQL AND & OR Operators

The AND operator displays a record if both the first condition AND the second condition are
true.

The OR operator displays a record if either the first condition OR the second condition is
true.
Combining AND & OR

You can also combine AND and OR (use parenthesis to form complex expressions).

The following SQL statement selects all customers from the country "Germany" AND the city
must be equal to "Berlin" OR "München", in the "Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Germany'
AND (City='Berlin' OR City='München');

Unit 9- Databases 161 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Database:

May/June 2007:

1 Explain, using examples where appropriate, the meaning of these computer terms.
(b) relational database [2]

Oct/Nov 2006:
A car dealer uses a database to keep details of cars in stock. Part of the stock file is shown
below.

(a) (i) State the fieldname that should be used as the key field.
(ii) Explain the purpose of a key field.
(b) The following search condition is input:
(Price($) < 5000) AND (Model = Golf)
Write down the records that match the above search condition using only RegNo.
(c) Write down a search condition to find cars with an Engine greater than 1400cc or which
have less than 5 Doors.
(d) When a car is sold, the sale needs to be linked to a customer file. Suggest a new field
which could be used to link the stock file to the customer file.

May/June 2007:
A hospital has decided to computerise its administration system.
(a) Give three ways this could affect the hospital workers.
The hospital will be using a database which holds confidential personal data.
(b) State two precautions that the hospital should take to prevent unauthorised access to
the data.
(c) Describe how the database could be recovered if it became corrupted.
(d) Give one example, in each case, of when it would be necessary to amend data,
delete data and insert data into the patient database.

Oct/Nov 2007:
A school Science department is going to use a database to record details about its
equipment.
(a) Give two advantages of using a computer system rather than a manual filing system.
(b) Part of the database is shown below:

(i) As data is entered it needs to be verified. Describe one way this could be done.

Unit 9- Databases 162 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

(ii) Data also needs to be validated. Using fields from the database as examples, describe
two different validation checks which could be performed on the data.

Oct/Nov 2008:

To gain access to a database, a user must first type in a user ID and then a password which
needs to be verified.
(a) How is a password usually verified?
(b) In spite of these safeguards, unauthorised access to the database is still possible.
What could be done:
(i) to prevent data being used by unauthorised people?
(ii) to prevent loss of data once the database has been illegally accessed?
(c) Personal data is protected to some extent by a Data Protection Act. Give two
requirements of a Data Protection Act.

Oct/Nov 2008:

15) A database has been produced showing solar system statistics.

(a) How many records are there in this database?


(b) The following search condition was typed in:
(Number of moons > 0) AND (Diameter (km) < 15000)
Using Name of planet, write down the results of this search:
(c) Write down a search condition to find out which planets have rings or have a diameter
more than 50000 km.
(d) Name a different validation check for each of the following fields.
(i) Maximum surface temperature (0C)
(ii) Name of planet
(e) The data in the database was sorted in descending order using the Number of moons
field. Using Name of planet only, write down the results of this sort.

Oct/Nov 2009:
A radio station keeps a database of all its music CDs. Here is part of this database:

Unit 9- Databases 163 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

(a) How many records are there in the database section?


(b) If the following query was input:
(CD length (mins) < 60) AND (number of hit tracks > 1)
using Reference Number only, write down which data items would be output.
(c) Write down a query to select which CDs are special edition or have more than 10
tracks.
(d) The database is sorted in descending order on CD length (mins). Using Reference
Number only, write down the order of the records following this sort.
(e) The radio station has a phone-in service where a listener texts the title of the CD on their
mobile phone. The popularity of each CD is then known and which CDs the radio station
should play.
(i) How would this information be stored?
(ii) How could this information be linked to the database?

May/June 2009:

Explain, using examples where appropriate, the meaning of these computer terms.
(b) relational database

May/June 2009:

17 A car sales company uses a database.


Here are three tables from the database:

(a) How many records are shown in the Customer Details table?
(b) (i) Which field connects the New Car Sales table with the Customer Details table?
(ii) Which field connects the New Car Sales table with the Car Manufacturer table?
(c) Give two reasons why List of Extras in the Car Manufacturer table is stored in code form.
(d) A customer goes into the showroom and the salesperson keys in 162154. What fields
and information would be shown on the output screen?
(e) Give one advantage to the car sales company of holding customer information on a
database.

Unit 9- Databases 164 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2010 P11:

A database has been set up to bring together information about the world‟s tallest
buildings.
A section of the database is shown below.

(a) How many records are in the section of the database shown?
(b) (b) Using Ref No. only, which records would be output if the following search
condition was entered:
(Year < 1990) AND (Height (m) > 375)?
(c) Write down a search condition to find out how many buildings are in China or how
many buildings have more than 80 floors.
(d) For each of the following fields give a different validation check.
Year
Ref No.
(e) The database was sorted in descending order of Year. Using Ref No. only, write down
the results of the sort:

May/June 2010 P12:

11 A database has been set up showing information about cars:

(a) Using Car ref only, write down which cars would be output if the following search
condition was used:
(No of doors = 4) AND (Fuel used (km/litre) > 15)
(b) Write down a search condition to find out which cars have engines larger than 1.8 litres
OR have CO2 emissions higher than 150 g/km.
(c) The database is sorted in ascending order on Fuel used (km/litre). Using Car ref only,
write down the results of the sort.

Unit 9- Databases 165 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2010:

10 A database has been set up to store information about aircraft. A section is shown
below.

(a) How many fields are in each record?


(b) Using Ref No only, what records would be output if the following search condition was
entered:
(Max Weight(kg) > 350 000) AND (Wing Span(m) < 66)?
(c) Write down the search condition to find out which aircraft have a length greater than
74 metres or have a maximum speed less than 900 kph.

14 An international bank keeps records of customer account details on a computer.


(a) It is necessary on occasions to:
• delete records
• amend records
• insert records
Give one example of when each of the above would need to be done. [3]
(b) A section of one record is shown below:

(i) The branch and country are coded. Give a reason for this. [1]
(ii) One of the six fields is not appropriate.
Name this field and give a reason for your choice. Suggest an improved field.
Name of field
Reason for choice
Improved field choice [3]

Unit 9- Databases 166 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2011:

A database showing the population of world cities has been produced. A section of the
database is shown below.

(a) How many records are shown above?


(b) Using Ref No only, which records would be found if the following search condition was
typed in
(Country = “India” OR Area = “America”) AND (Capital = “No”)
(c) Write a search condition to find the cities in Asia with a city population greater than 17
million OR an urban population greater than 20 million.
(d) Give one advantage of using Y or N rather than Yes or No in the Capital column.

Oct/Nov 2011:

An airport has a number of hotels nearby. A database has been set up to give customers
information to allow them to select a hotel.

(a) How many records are shown in the database?


(b) Which field in each record must be unique?
(c) The following search condition was typed in:
(No. of stars > 3) OR (Hotel parking = Y)
Using Hotel Ref only, which records would be found?
(d) Write down the search condition to find which hotels were less than 10 km from the
airport and charged under $100 per person.
(e) The database was sorted into descending order using No. of rooms.
Using Hotel Ref only, write down the sorted order of records.

Unit 9- Databases 167 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2011:

A database has been set up to show details about countries. Part of the database is shown
below.

(a) How many fields are in each record?


(b) Using Country code only, what would be output if the following search condition was
used?
(Population (millions) > 1000) OR (Continent = “Asia”)
(c) Write down a search condition to find which countries have a land area less than 3
million square km and also have a coastline.
(d) If the database was sorted in descending order of population size, using Country code
only, what would be the order of countries in the database?

May/June 2012:

A database was set up to show the properties of certain chemical elements. Part of the
database is shown below.

(a) How many fields are in each record?


(b) The following search condition was entered:
(Melting Point (C) < 40) AND (Atomic Weight > 100)
Using Element Symbol only, which records would be output?
(c) We need to know which elements have an atomic number greater than 50 and are
solid at room temperature.
Write down the search condition to find out these elements.
(d) The data are to be sorted in descending order of Boiling Point (C).
Write down the new order of records using the Element Symbol only.

Unit 9- Databases 168 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

Oct/Nov 2012:

A database was set up showing the largest ocean-going liners. Part of the database is
shown below.

(a) How many records are shown in the above part?


(b) Using Liner ID only, what would be output if the following search condition was typed in:
(Year built < 2000) AND (Country of Registration = Country of Construction)?
(c) Write the search condition to find out which liners have a gross tonnage larger than 80
000 or are registered in the UK.

May/June 2013:

A database was set up to compare oil companies. A section of the database is shown
below:

(a) How many fields are there in each record?


(b) The following search condition was entered:
(No of countries < 30) AND (Head office = “Americas”)
Using Code only, which records would be output?
(c) What search condition is needed to find out which oil companies have a share price
less than $50 or whose profits were greater than 8 billion dollars?

Unit 9- Databases 169 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

May/June 2013:
A survey of motorways was carried out and a database was produced. A section of the
database is shown below.

(a) How many fields and how many records are shown?
(i) number of fields
(ii) number of records
(b) Using Motorway ID only, what would be output if the following search condition was
used?
(Length (km) > 100) AND (Number of lanes > 3)
(c) What search condition is needed to find the motorways where the number of cars per
day exceeds 50 000 or the toll charge per kilometre is greater than $0.50?

Oct/Nov 2013 P12:


3 A motor car manufacturer offers various combinations of
• seatcolours
• seat materials
• car paint colours
A database was set up to help customers choose which seat and paint combinations were
possible.

(NOTE: N = no, not a possible combination, Y = yes, combination is possible)


(a) How many records are shown in the database? [1]
(b) The following search condition was entered:
(cloth= “Y”) AND (blue = “Y”)
Using code only, which records will be found? [2]

Unit 9- Databases 170 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

(c) A customer wanted to know the possible combinations for a car with leather seats and
either silver or grey paint colour.
What search condition would need to be input? [2]
(d) A customer decided to buy a green car. He wanted to know which seat colours and
seat materials were not a possible combination with green paint.
What search condition would he need to enter? [1]
(e) Give one advantage of using the codes Y and N in the database rather than using Yes
and No. [1]

Oct/Nov 2013 P13:

9 A database was set up to keep track of goods in a shop. A section of the database is
shown below.

(a) How many records are shown in this section of database? [1]
(b) (i) Using Item code only, what would be output if the following search was carried
out:
(Number in stock <Re-order level) AND (Items ordered = “No”) [2]
(ii) What useful information does this search produce? [1]
(c) Write a search condition to locate items costing more than $2.00 or have a stock value
exceeding $300.00. [2]

May/June 2014 P11:

3 A hospital holds records of its patients in a database. Four of the fields are:
• date of visit (dd/mm/yyyy)
• patient‟s height (m)
• 8-digit patient ID
• contact telephone number
The presence check is one possible type of validation check on the data. For each field,
give another validation check that can be performed. Give an example of data which
would fail your named validation check.
A different validation check needs to be given for each field.

Unit 9- Databases 171 | P a g e


Notes for O Level Computer Science 2210 By Farhan Rahmat

14 A database was set up showing statistics for some states in the USA. Part of the
database is shown below.

(a) (i) How many records are in this section of the database? [1]
(ii) How many fields are in each record? [1]
(b) The following search condition was entered:
(Population (millions) < 4.0) OR (Number of houses (millions) < 4.0)
Using Ref only, write down which records will be found. [2]
(c) Write down the search condition to find out which states have an area over 100 000
square miles and where it takes less than 25 minutes to get to work. [2]
(d) (i) What should be the key field in this database? [1]
(ii) Give a reason for your choice.

Unit 9- Databases 172 | P a g e

You might also like