O LevelComputer - Ruknuddin Patel`s Web Portal

Transcription

O LevelComputer - Ruknuddin Patel`s Web Portal
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
2.1.2 Pseudocode
• understand and use pseudocode for assignment, using ←
• understand and use pseudocode, using the following conditional statements:
IF … THEN … ELSE … ENDIF
CASE … OF … OTHERWISE … ENDCASE
• understand and use pseudocode, using the following loop structures:
FOR … TO … NEXT
REPEAT … UNTIL
WHILE … DO … ENDWHILE
• understand and use pseudocode, using the following commands and statements:
INPUT and OUTPUT (e.g. READ and PRINT)
totalling (e.g. Sum ← Sum + Number)
counting (e.g. Count ← Count + 1)
(Candidates are advised to try out solutions to a variety of different problems on a computer using a
language of their choice; no particular programming language will be assumed in this syllabus.)
Introduction to Algorithm
An algorithm is a sequence of steps for solving a problem.
In general, an 'algorithm' is the name given to a defined set of steps used to complete a task.
For instance you could define an algorithm to make a cup of tea. You start by filling the kettle, then place a tea bag
in the cup and so on.
In computer terms, an algorithm describes the set of steps needed to carry out a software task. This mini-web takes
you through the topic of algorithm
Creating a plan
The main stages of planning any solution are:
• understanding the problem
• defining the scope of a solution – the extent of the facilities that the solution will provide
• creating the solution
• documenting the solution
• testing the solution.
Creating the solution
This involves:
• top-down design or stepwise refinement
• algorithms, which can be represented as
– program flowcharts
– pseudocode
• modules of code
• menus.
Document the solution
Techniques for documenting an algorithm include:
• structure diagrams
• program flowcharts (for symbols, see Table 9.1 in coursebook).
For documenting the hardware required in a solution while showing much less processing detail, we can
use system flowcharts, which have a much larger set of symbols.
Testing and interpreting algorithms
Computer Science by Inqilab Patel
Page 1
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
Dry running is the process of thinking through the operation of an algorithm, to test it during design, for
troubleshooting and to work out its purpose, if not stated.
A trace table is a tabular record of a dry run. It has a column for each variable, usually in the order in
which their values are first assigned. Each row is completed with the values of the variables whenever
they change, moving to the next row when necessary.
Computer Science by Inqilab Patel
Page 2
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
The concept of a program
A program is a sequence of instructions or programming language statements written to make a
computer perform certain tasks.
Well-structured programs require a programming language to support the following program
constructs:
• sequence
• selection
• iteration
A computer’s processor can only run a computer program in the form of a file of machine code,
which is a sequence of binary codes representing instructions for the processor.
The instruction set for a family of processors is the machine language in which machine code is
written for that family of processors.
When machine code runs, the processor repeatedly:
• fetches an instruction from internal memory
• decodes the instruction
• executes the instruction.
Pseudocode
Pseudocode uses keywords commonly found in high-level languages and mathematical notation. It
describes an algorithm’s steps like program statements, without being bound by the strict rules of
vocabulary and syntax of any particular language, together with ordinary English.
Variable:
Variable is memory location where a value can be stored.
Computer Science by Inqilab Patel
Page 3
ruknuddin.com
O LevelComputer
Inqilab Patel
2.1: Algorithm & Pseudocodes
Arithmetic
Use the arithmetic operators.
Assignment
Assignment is the process of writing a value into a variable (a named memory location). For
example, Count ← 1 can be read as ‘Count is assigned the value 1’, ‘Count is made equal to 1’ or ‘Count
becomes 1’. Another way of indicating assignment is a pseudocode statement such as:
set Swapped to False
Initialisation:
If an algorithm needs to read the value of a variable before it assigns input data or a calculated value
to the variable, the algorithm should assign an appropriate initial value to the variable, known as
Initialisation.
Input
We indicate input by words such as INPUT, READ or ENTER, followed by the name of a variable to
which we wish to assign the input value.
Output
We indicate output by words such as OUTPUT, WRITE or PRINT, followed by a comma-separated list
of expressions.
Totalling
To keep a running total, we can use a variable such as Total or Sum to hold the running total and
assignment statements such as:
Total ← Total + Number
ADD Number to Total
Counting
It is sometimes necessary to count how many times something happens.
To count up or increment by 1, we can use statements such as:
Count ← Count + 1
INCREMENT Count by 1
Structured statements for iteration (repetition or loops)
Many problems involve repeating one or more statements, so it is useful to have structured
statements for controlling these iterations or repetitions. Exit conditions consist of logical expressions
whose truth can be tested, such as Count = 10 or Score < 0. At a particular time, a logical expression is
either True or False.
• WHILE…DO…ENDWHILE
• REPEAT…UNTIL
• FOR…TO…NEXT
Structured statements for selection (conditional statements)
These statements are used to select alternative routes through an algorithm, using logical
expressions as conditions for the decisions involved. As with iteration (repetition), selection’s logical
expressions often involve comparisons, which can operate on text strings as well as numbers.
• IF…THEN…ELSE…ENDIF
• CASE…OF…OTHERWISE…ENDCASE
Producing algorithms in pseudocode
Writing an algorithm in pseudocode is no longer graphical like a program flowchart, but is one step
closer to writing program code in a high-level language.
Producing an algorithm for a solution in pseudocode typically includes:
Computer Science by Inqilab Patel
Page 4
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
• initialising any variables for totalling and counting
• using REPEAT…UNTIL for input validation
• using an appropriate loop structure for repetitions of data entry and/or other processing
• using conditional statements to select appropriate processing alternatives
• IF…THEN…ELSE…ENDIF statements for adjusting the values of maximum and minimum variables
cannot be nested.
Testing and interpreting pseudocode algorithms
Dry running a pseudocode algorithm with a trace table and test data helps to understand its
behaviour and purpose.
Trace Table
Trace Table has columns for all variables, logical expressions and output.
Example interpretation
The purpose of the algorithm is to print a list of the powers of 2 starting at 20 until it reaches the
first one over 100.
Computer Science by Inqilab Patel
Page 5
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
Finding and correcting errors in pseudocode algorithms
It is important to be able to identify errors and suggest corrections in a pseudocode algorithm.
Common errors in pseudocode algorithms include:
• missing or faulty initialisation of variables
• faulty initial and final values for the control variable (loop counter) in a FOR…TO…NEXT loop
• incrementing the loop counter in a FOR…TO…NEXT loop, which interferes with the
automatic counting
• failing to increment an optional counter variable in the other sorts of loop
• failing to complete a structured 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.
Questions:
1 Write an algorithm to calculate the average of ten numbers. (Average = Total of the ten numbers
divided by 10.)
2 What is the difference between machine code and a program written in a high-level language?
3 Write an algorithm which will input a sequence of eight numbers between 1 and 1,000,000, and
print a list of all eight numbers together with the largest and smallest number in the list.
4 List four high-level programming languages.
5 Read this algorithm.
SET Result to 0
INPUT Number
WHILE Number >= 0
DO
IF Number > Result THEN Result  Number
INPUT Number
ENDWHILE
OUTPUT Result
a What is the purpose of this algorithm?
b What value of input will stop the loop and output the answer?
c Copy and complete the following trace table for the input values 6, 12, 8 and −3.
Result
Number
OUTPUT
1. Sum  0
FOR Count  1 TO 10
INPUT Number
Sum  Sum + Number
NEXT
OUTPUT “Average = “, Sum / 10
Computer Science by Inqilab Patel
Page 6
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
2 Machine code is a program written in machine language that can be understood by a specific
processor family. A program in a high-level language can be run on a number of different processors
but must be converted to machine code by a compiler or executed by an interpreter.
4 COBOL, Delphi, C++ and Java are high-level programming languages.
5 a The algorithm inputs a sequence of numbers and keeps a record of the largest number read so
far. Once the loop ends, it outputs the largest number input.
b Any value less than 0 stops the loop and outputs the answer.
Winter 2001
Q10) This algorithm grades candidates on marks out of ten.
1 input a Mark
2 case Mark of
3 0, 1, 2, 3 : Grade = Fail
4 4, 5 : Grade = Pass
5 6, 7 : Grade = Merit
6 8, 9, 10 : Grade = Distinction
Computer Science by Inqilab Patel
Page 7
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
7 otherwise Mark = -1
8 endcase
9 if Mark = -1 then
10 print ‘Not a valid mark’
11 else output Grade, ‘Grade’
(a) Dry run the algorithm for each of the following data and complete the table.
[3]
(b) Write down two instructions which could be inserted between lines 1 and 2 to allow the algorithm to
deal with marks out of 100.
[2]
Q14) (a) State two advantages for a computer having several high-level languages.
1. ..................................................................................................................................
2................................................................................................................................ [2]
(b) State two reasons why assembly language is still used.
1. ..................................................................................................................................
2................................................................................................................................ [2]
(c) Using an example, or otherwise, show the difference between a Repeat …Until construct and an
If ... then ... Else … Endif construct.
Repeat …Until .........................................................................................................................
If ... then ... Else … Endif ....................................................................................................[4]
Winter 2002
Q13 Read this algorithm.
set Total_1 to zero
set Total_2 to zero
set Counter to one
while Counter < eight
Counter = Counter + 1
input Number
if Number > zero then Total_1 = Total_1 + Number
if Number < zero then Total_2 = Total_2 + Number
endwhile
output Total_1
output Total_2
(a) Write down the output if the following set of numbers are input. 4, 1, -3, 2, -5, 0, 6 [2]
(b) Modify the algorithm so that it will accept any number of numbers, the input is terminated by a
rogue value and the output is the Total of all the numbers input except the rogue value. [4]
Computer Science by Inqilab Patel
Page 8
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
Summer 2003
Q13 Read this algorithm.
input A, B
if A > B then
T=A
A=B
B=T
endif
output A, B
(a) Write down the output if the following two numbers are input:
41, 38 ...............................................................................................................................[1]
(b) Explain the purpose of the variable T ....................................................................... [1]
(c) Explain why an algorithm is written as a subroutine (procedure) and stored in a program library.
...........................................................................................................................[2]
Winter 2003
Q11 The following algorithm inputs air speeds (which must be in multiples of 100) and outputs a
suitable message.
1 input a speed
2 whole = speed/100
3 case whole of
4 0,1,2 : result = slow
5 3, 4, 5, 6 : result = normal
8 7, 8, 9 : result = high
7 otherwise whole = -1
8 endcase
9 if whole = -1 then
10 output “abnormal reading”
11 else output result, “speed”
Dry run the above algorithm for the following Input data and complete the Output column in the table:
[3]
Input
Output
150
400
800
State what would be happen if line 2 had been missed out of the algorithm?
[2]
Summer 2005
Q13 The following algorithm contains an error.
1. SET X = 1
Computer Science by Inqilab Patel
Page 9
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
2. REPEAT
3. X = X + 2
4. Print X
5. UNTIL X = 10
(a) Trace the algorithm and explain what the error is.
[2]
(b) Write an algorithm which uses a While..Do..Endwhile loop and outputs the numbers 2, 4, 6 and 8[3]
Winter 2006
Q9) 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.
A while do loop has been used in the algorithm. State another type of loop that could have been used.
Summer 2008
Q12) Algorithms and programs use loops to control the number of times a particular procedure is used.
Two methods are repeat … until and for … to.
(a) Write a procedure using both these loop methods to input 20 numbers into a variable called x.
(i) repeat … until
[2]
(ii) for … to
[2]
(b) Name another loop structure.
[1]
Winter 2008
Q3) Write a routine using a for … to loop which inputs 100 numbers and outputs how many of the
numbers were negative.
[3]
Summer 2010
Q13) A golf course charges $10 for each game of two people. Each additional person incurs a further
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
Computer Science by Inqilab Patel
Page 10
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
4
extrapeople = numberpeople – 2
5
if numberpeople < 2 then extracost = 2 * extrapeople * numbergames
6
charge = extracost
7
if numbergames
mbergames > 1 then charge = charge * 0.1
8
print charge
There are three errors in the program. Locate these errors and suggest a correct piece of coding.
Error 1
Correction 1
Error 2
Correction 2
Error 3
Correction 3
[6]
Winter 2010
Q9) 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.
Error 1
Reason 1
Error 2
Reason 2
Error 3
Reason 3
[6]
Summer 2011
Q 7 a) Read the following section of code that inputs twenty (20) numbers and then outputs the largest
number input.
1h=0
2c=0
3 REPEAT
4 READ x
Computer Science by Inqilab Patel
Page 11
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
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 piece of code.
1, 2, 3
[3]
Summer 2012
Q10c) A different application needs the whole PIN to be input.
The following code has been written to check the PIN:
c=0
INPUT PIN
x = PIN
REPEAT
x = x/10
c=c+1
UNTIL x < 1
IF c < 5
THEN
PRINT “error in PIN entered”
ELSE
PRINT “PIN OK”
ENDIF
(i) What value of c and what message would be output if the following PINs were entered?
5 1 0 2 0 Value of c:
Message:
5 1 2 0 Value of c:
Message: [2]
(ii) What type of validation check is being carried out here?
[1]
Winter 2013
Q8) A piece of pseudocode was written to input 1000 positive numbers and then output the highest
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
Computer Science by Inqilab Patel
Page 12
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
80 next count
90 print highest, lowest
There are errors in the code.
Locate these errors and suggest a correction.
Error 1, 2, 3, 4
Correction
Specimen 2015
Q 2) Jatinder uses Internet banking. This pseudocode checks her PIN.
c←0
INPUT PIN
x ← PIN
REPEAT
x ← x/10
c←c+1
UNTIL x < 1
IF c <> 5
THEN
PRINT “error in PIN entered”
ELSE
PRINT “PIN OK”
ENDIF
(a) What value of c and what message would be output if the following PINs were entered?
5 1 0 2 0 Value of c:
Message:
5 1 2 0 Value of c:
Message: [2]
(b) What type of validation check is being carried out here?
[1]
Q4 Read this section of program code that inputs twenty (20) numbers and then outputs the largest
number 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 piece of code.
1, 2, 3
[3]
Computer Science by Inqilab Patel
Page 13
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
9691_09s_p1
Q4)
1X=1
2 REPEAT
3
A=X*X
4
OUTPUT X, A
5
X=X+1
6 UNTIL X = 3
7 END
(a) Copy and complete the following table to dry run the algorithm.
LINE X
A
OUTPUT
CONDITION
1
1
3
1
1
[4]
(b) The algorithm outputs consecutive numbers, starting with 1, and their squares. The intention
was to print out the first 10 numbers with their squares.
(i) State how the algorithm needs to be changed in order to print 10 numbers, as intended. [1]
(ii) Explain how the algorithm can be changed to allow the user to specify how many numbers
are to be output. [2]
(b) Rewrite the algorithm so that it will output the numbers 5, 10, 15, 20, 25, with their
squares.[3]
Writing Algorithm
Summer 2015 Specimen)
6 (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)
Winter 2013
16 (a) A greenhouse is being monitored by a computer using 2 sensors. SENSOR1 measures
the temperature and SENSOR2 measures oxygen levels.
If the temperature exceeds 45°C or oxygen levels fall below 0.19, then an error message 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).
Computer Science by Inqilab Patel
Page 14
ruknuddin.com
O LevelComputer
Inqilab Patel
2.1: Algorithm & Pseudocodes
Summer 2013
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
Writing algorithms using pseudocode:
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.
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.
Computer Science by Inqilab Patel
Page 15
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
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).
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).
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)
Problems
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
Computer Science by Inqilab Patel
Page 16
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
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.
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.
Computer Science by Inqilab Patel
Page 17
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
(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!!).
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)
speed =
(metres/sec)
Computer Science by Inqilab Patel
Page 18
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
Summer 2001
16 Employees of a shop are entitled to a discount of 10% on the value of goods bought from the
shop. However if an employee has worked at the shop for five or more years they are entitled to
a discount of 20%. Only employees are allowed discounts. The discount on electrical goods is
fixed at only 10%.
Using pseudocode or otherwise, write an algorithm which will determine what discount applies
when any person buys an item.
Summer 2001
16 Using pseudo code or otherwise, write an algorithm which will take information about each
transaction at a supermarket till, calculate and output
• the number of sales,
• the number of refunds,
• the total amount of money in the till.
Winter 2002
19 Using pseudo code or otherwise, write an algorithm which will input any three different
numbers and then print them out in ascending order.
Summer 2003
17 A school wants to monitor the number of hours spent by a class of 30 students on the
Internet.
Using pseudocode or otherwise, write an algorithm which will;
• for each student, record the times logged on and logged off
• calculate the length of time each student spends online
• calculate and output the average length of time per day spent by each student on the Internet.
Winter 2003
16 (a) Write an algorithm, using pseudocode or otherwise, which;
• inputs 50 numbers
• checks whether each number is in the range 1000 to 9999
• outputs how many of the input numbers were out of range
• outputs the percentage of input numbers which were out of range.
Summer 2004
15 (b) Using pseudocode, or otherwise, write an algorithm that will input the hourly
temperatures for one day in Centigrade and print out in Fahrenheit
• the maximum temperature
• the minimum temperature
• the average temperature for that day.
Computer Science by Inqilab Patel
Page 19
ruknuddin.com
O LevelComputer
Inqilab Patel
2.1: Algorithm & Pseudocodes
Winter 2004
19 The following diagram shows a rail network.
The rail network consists of 10 stations. The fare between each station is $2. There is a 10%
discount when 3 or more passengers travel together. Tickets can be purchased at any station
using automated terminals.
Using pseudocode, or otherwise, write an algorithm for the automated terminals to:
• input the starting station number, the destination station number and the number of
passengers
• calculate the total fare and output the amount to be paid
• calculate the change (if any)
• issue the rail ticket(s) and change
Summer 2005
17 Using pseudocode or otherwise, write an algorithm that will input 25 marks and output the
number of DISTINCTION, MERIT, PASS or FAIL grades.
A mark greater than 69 will get a DISTINCTION, a mark between 69 and 60 (inclusive) will get a
MERIT and a mark between 59 and 50 (inclusive) will get a PASS.
Winter 2005
17 A school uses a computer to store student marks obtained in an end of term mathematics
exam. There are 150 students doing the exam and the maximum mark is 100.
Write an algorithm, using pseudocode or otherwise, which
• inputs the marks for all students
• checks if each mark is in the correct range and, if not, the mark is re-input
• outputs the smallest mark
• outputs the highest mark
• outputs the average mark for the exam.
Summer 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 meters.
Computer Science by Inqilab Patel
Page 20
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
(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’.
Winter 2006
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
Summer 2007
19 A company has 5000 CDs, DVDs, videos and books in stock. Each item has a unique 5-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 the 3
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.
Winter 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?
(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)
Computer Science by Inqilab Patel
Page 21
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
Summer 2008
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.
Winter 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).
Summer 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
Winter 2009
17 (a) A car’s speed is measured between points A and B, which are 200 km apart.
Computer Science by Inqilab Patel
Page 22
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
What is the final speed of a car if it takes 2 hours to get from A to B?
(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.
Summer 2010
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
16 (a) Write an algorithm, using pseudocode or a flowchart, which:
_ inputs 50 numbers
_ outputs how many of the numbers were > 100
(b) Write an algorithm, using pseudocode or a flowchart, which:
_ inputs 100 numbers
_ finds the average of the input numbers
_ outputs the average
Winter 2010
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
Computer Science by Inqilab Patel
Page 23
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
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
(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)
Specimen 2011
19 The exchange rate between the US Dollar (US$) and the Brazilian Real (R$) changes every
day.
Write an algorithm, using pseudocode or otherwise, which inputs the exchange rate for every
day over a 10 year period (assume that each year = 365 days) and then outputs the following:
• The average (mean) exchange rate
• The best (highest) exchange rate
• The worst (lowest) exchange rate
• The number of occasions when the exchange rate was above 2.0
Summer 2011
17 Daniel lives in Italy and travels to Mexico, India and New Zealand. The times differences are:
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
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
Computer Science by Inqilab Patel
Page 24
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
Winter 2011
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)
16 The weather conditions in a town are being monitored over a year (365 days). The values
recorded 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
Summer 2012
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.
15 An estate agent advertises houses for sale. The customer enquiries for a 7-day working
week 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 costing more than
$500 000.
Winter 2012
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.
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
Computer Science by Inqilab Patel
Page 25
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
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.
Summer 2013
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
17 A country has four mobile phone network operators. Each mobile phone number has eight
digits. 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-digit mobile
phone calls made during the day and outputs the number of calls made on each of the four
networks.
Winter 2013
16 (a) A greenhouse is being monitored by a computer using 2 sensors. SENSOR1 measures
the temperature and SENSOR2 measures oxygen levels.
If the temperature exceeds 45°C or oxygen levels fall below 0.19, then an error message 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
Computer Science by Inqilab Patel
Page 26
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
• 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).
15 5000 numbers are being input which should have either 1 digit (e.g. 5), 2 digits (e.g. 36), 3
digits (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
9691 Winter 2009
10 Part of the processing of the data is to calculate the amount of tax which needs to be paid.
• The person’s total income for the year is input to the system
• The first $500 is not taxed
• The remainder is taxed at 10%
• Either the tax to be paid is output from the system OR a message is output to say there is no
tax to pay
(a) Using I to stand for the total income and T to stand for the tax to be paid, produce an
algorithm which will take I as its input and then calculate the tax. [5]
8 Candidates are advised to use either pseudo code or a flow diagram to answer this question,
although other forms of algorithmic representation will be credited.
The automated snack bar is a machine.
The machine advertises 10 snack items; each one is given a number from 0 to 9.
The user presses one of the buttons from 0 to 9 on the front of the machine. The machine
checks in an array in its memory to find the price of the snack selected. This price is displayed
on the front of the machine.
The customer then inserts 1-cent and/or 5-cent coins. Each time a coin is input the machine
subtracts the value from the amount still required. The display changes to show the new amount
still required.
When enough coins have been inserted the machine will deliver the item and pay out any
change necessary.
Write an algorithm to control the process of buying a snack. [9]
9691 Summer 2010
9 Candidates are advised to use either pseudocode or a flow chart to answer this question,
although other forms of algorithmic representation will be credited.
Individual statements are produced each month for customers.
(a) A procedure is to be written which inputs data from a customer record, totals the amount
outstanding on orders which have been dispatched but not yet paid for, and outputs details of
these orders.
Produce an algorithm which will carry out the above task. The procedure is to be called
INVOICE. [4]
(b) The amount that the customer pays depends on the type of customer.
Computer Science by Inqilab Patel
Page 27
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
Each customer receives a gold, silver or bronze discount. This discount is recorded in the
customer record.
A gold customer receives a 20% discount.
A silver customer receives a 10% discount.
A bronze customer receives a 5% discount.
The discounted amount should be output after the total calculated in INVOICE, with a suitable
explanation.
Produce the final algorithm that will print out the customer statements. (You should use
INVOICE in this final algorithm without reproducing the details from part (a).) [7]
9 Candidates are advised to use either pseudocode or a flow chart to answer this question,
although other forms of algorithmic representation will be credited.
Individual statements are produced each month for customers.
(a) A procedure is to be written which inputs data from a customer record, totals the amount
outstanding on orders which have been dispatched but not yet paid for, and outputs details of
these orders.
Produce an algorithm which will carry out the above task. The procedure is to be called
INVOICE. [4]
(b) The amount that the customer pays depends on the type of customer.
Each customer receives a gold, silver or bronze discount. This discount is recorded in the
customer record.
A gold customer receives a 20% discount.
A silver customer receives a 10% discount.
A bronze customer receives a 5% discount.
The discounted amount should be output after the total calculated in INVOICE, with a suitable
explanation.
Produce the final algorithm that will print out the customer statements. (You should use
INVOICE in this final algorithm without reproducing the details from part (a).) [7]
9 Candidates are advised to use either pseudocode or a flow chart to answer this question,
although other forms of algorithmic representation will be credited.
(a) Students take exams in all their subjects at the end of every year. A procedure is to be
written which inputs the marks of a student from the STUDENT file and calculates the mean
mark for that student.
Produce an algorithm which will carry out the above task. The procedure is to be called MEAN.
[4]
(b) The school awards a prize each year to the students who achieve the highest mean mark in
their form.
Produce an algorithm for a procedure called PRIZE which will determine which student will win
the prize for a particular form. The name of the form and the name of the student should then be
saved to a file called PRIZES.
(You should use MEAN in this final algorithm without reproducing the detail in part (a).) [7]
9691Winter 2010
7 A piece of software is written to interrogate past records of summer temperatures to find
evidence for global warming.
Computer Science by Inqilab Patel
Page 28
ruknuddin.com
O LevelComputer
2.1: Algorithm & Pseudocodes
Inqilab Patel
The software needs to read the average summer temperature for each year from 1900 to 2009.
It must work out the mean (M) of these average summer temperatures for the 110 years.
The user can now enter any year from 1900 until 2006. The software will calculate the mean of
the temperatures over a four year period, starting from that year. (For example, if 2000 is
entered, then the mean of the temperatures for 2000, 2001, 2002 and 2003 is calculated.) If this
mean is more than 4 degrees higher than M, it will then report “Hot”.
Produce an algorithm for the software. [10]
7 An algorithm is to be created to calculate the pay for the workers in a factory.
The name of each worker is input with the number of hours worked that week. Workers are paid
in Lienes and cents, a Liene being local currency.
100 cents = 1 Liene
Each worker is paid 2.85 Lienes per hour. If a worker earns more than 80 Lienes in a week they
must pay 20% of anything over 80 Lienes in tax. Their pay is then reduced by that amount.
Produce an algorithm for the software which will output for each worker: their name; their pay for
the week; the tax they must pay.
The algorithm will continue to calculate the pay of workers until the value 'xxx' is input as the
worker's name.
The number of workers should be output at the end of the algorithm. [10]
Summer 2014 P11
15 A survey is being carried out which involves reading and recording sound levels near a busy road
junction. Once all the data are collected, they are input manually into a computer. A sound level of 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.
Summer 2014 P12
18 A school has 1500 students. It is conducting a survey on their music preferences. Each student
uses 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.
Computer Science by Inqilab Patel
Page 29
ruknuddin.com