Documente Academic
Documente Profesional
Documente Cultură
A-Level
Computer Sciece
Paper 41
With Marking Scheme
From 2015(M/J) To 2019(M/J)
2
This material is intended to be read by teachers and candidates prior to the June 2015 examination for
9608 Paper 4.
Reminders
The syllabus states:
• there will be questions on the examination paper which do not relate to this pre-release material
• you must choose a high-level programming language from this list:
• Visual Basic (Console Mode)
• Python
• Pascal / Delphi (Console Mode)
The practical skills covered in Paper 2 are a precursor to those required in Paper 4. It is therefore
recommended that the high-level programming language chosen for this paper is the same as that for
Paper 2. This allows for sufficient expertise to be acquired with the opportunity for extensive practice.
TASK 1
A linked list Abstract Data Type (ADT) has these associated operations:
The linked list ADT consists of a linked list of nodes. Each node consists of data and a pointer to the
next node.
TASK 1.1
Consider the use of a linked list to store names in alphabetical order.
CreateLinkedList
AddName("Nabila")
AddName("Jack")
AddName("Kerrie") Key focus: Conceptual
AddName("Sara") diagrams of linked lists
RemoveName("Kerrie")
AddName("Zac")
Add appropriate labels to the diagram to show the final state of the linked list. Use the space on the left
as a workspace. Show your final answer in the node shapes on the right:
TASK 1.2
The linked list is to be implemented as an array of records, where each record represents a node.
The CreateLinkedList operation links all nodes to form the free list and initialises the HeadPointer
and FreePointer.
Complete the diagram to show the values of all pointers after the CreateLinkedList operation has
been carried out.
NameList
HeadPointer Name Pointer
[1]
[2]
[3]
[4]
[5]
FreePointer [6]
[49]
[50]
TASK 1.3
Complete the diagram to show the values of all pointers after the following operations have been
carried out:
AddName("Nabila")
AddName("Jack")
AddName("Kerrie")
AddName("Sara")
RemoveName("Kerrie")
AddName("Zac")
NameList
HeadPointer Name Pointer
[1]
[2]
[3]
[4]
[5]
FreePointer [6]
[49]
[50]
TASK 1.4
Complete the identifier table for the pseudocode given below.
01 PROCEDURE AddName(NewName)
02 // New name placed in node at head of free list
03 NameList[FreePointer].Name ←
NewName
04 NewNodePointer ←
FreePointer
05 FreePointer ←
NameList[FreePointer].Pointer
06
07 // initialise current pointer to start of list
08 CurrentPointer ←
HeadPointer
09
10 // check that it is not the special case of adding to empty list
11 IF HeadPointer > 0
12 // loop to locate position of new name
13 // saves current pointer and then updates current pointer
14 WHILE NameList[CurrentPointer].Name < NewName
15 PreviousPointer ←
CurrentPointer
16 CurrentPointer ←
NameList[CurrentPointer].Pointer
17 ENDWHILE
18 ENDIF
19
20 // check to see whether new name is first in linked list
21 // if first item then place item at head of list
22 // if not first item then adjust pointers to place it in correct
23 // position in list
24 IF CurrentPointer = HeadPointer
25 THEN
26 NameList[NewNodePointer].Pointer HeadPointer ←
27 HeadPointer ←
NewNodePointer
28 ELSE
29 NameList[NewNodePointer].Pointer ←
NameList[PreviousPointer].Pointer
30 NameList[PreviousPointer].Pointer ←
NewNodePointer
31 ENDIF
32 ENDPROCEDURE
TASK 1.5
Write program code for the pseudocode given in Task 1.4.
TASK 1.6
The structured English algorithm for the operation to remove a name from the linked list is as follows:
TASK 1.6.1
Write the algorithm, as a procedure in pseudocode, from the structured English given above.
TASK 1.6.2
Write program code from your pseudocode design.
TASK 1.6.3
Test your program code for creating a linked list, adding and removing names, using the data given in
Task 1.3.
Design pseudocode and write program code for these data structures.
TASK 2
The unique registration and the engine size (in litres, to the nearest 0.1 of a litre) are stored for all
vehicles.
Data stored about cars also include the hire charge per day (in $) and the number of passengers
allowed.
Data stored about trucks also include the hire charge per hour (in $) and the maximum payload (in kg).
Object-oriented software is to be written to process data about vehicles hired, including calculating the
hire fee.
The superclass (also known as base class or parent class) Vehicle is designed.
Two subclasses (also known as derived classes or child classes) have been identified:
• Car
Key focus: Object-oriented programming
• Truck
TASK 2.1
Complete the inheritance diagram.
TASK 2.2
Complete the class diagram showing the appropriate properties and methods.
........................................................................
........................................................................
........................................................................
........................................................................
........................................................................
........................................................................
........................................................................
....................................................................... .......................................................................
....................................................................... .......................................................................
....................................................................... .......................................................................
....................................................................... .......................................................................
Constructor() .......................................................................
....................................................................... .......................................................................
....................................................................... .......................................................................
....................................................................... .......................................................................
Note: a constructor is a method that creates a new instance of a class and initialises it.
TASK 2.3
Write program code for the class definitions. Make use of polymorphism and inheritance where
appropriate.
TASK 2.4
Write program code to create a new instance of Car.
TASK 3
An intruder detection system is inactive when the power is switched off. The system is activated when
the power is switched on. When the system senses an intruder the alarm bell rings. A reset button is
pressed to turn the alarm bell off and return the system to the active state.
The transition from one state to another is as shown in the state transition table below.
..............................
start
.............................. ..............................
..............................
..............................
.............................. ..............................
..............................
Write your Centre number, candidate number and name in the spaces at the top of this page.
Write in dark blue or black pen.
You may use an HB pencil for any diagrams, graphs or rough working.
Do not use staples, paper clips, glue or correction fluid.
DO NOT WRITE IN ANY BARCODES.
No marks will be awarded for using brand names of software packages or hardware.
At the end of the examination, fasten all your work securely together.
The number of marks is given in brackets [ ] at the end of each question or part question.
DC (NH/SG) 106699/3
© UCLES 2016 [Turn over
2
1 A linked list abstract data type (ADT) is to be used to store and organise surnames.
This will be implemented with a 1D array and a start pointer. Elements of the array consist of a
user-defined type. The user-defined type consists of a data value and a link pointer.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[3]
Write the pseudocode declaration statement for SurnameList. The lower and upper
bounds of the array are 1 and 5000 respectively.
.......................................................................................................................................[2]
(b) The following surnames are organised as a linked list with a start pointer StartPtr.
StartPtr: 3
1 2 3 4 5 6 5000
Surname Liu Yang Chan Wu Zhao Huang …
Ptr 4 5 6 2 0 1 …
(c) Pseudocode is to be written to search the linked list for a surname input by the user.
Complete the table above by adding the missing identifier details. [2]
01 Current ← ..............................................................................................................
02 IF Current = 0
03 THEN
04 OUTPUT .........................................................................................................
05 ELSE
06 IsFound ← .................................................................................................
07 INPUT ThisSurname
08 REPEAT
09 IF ............................................................................. = ThisSurname
10 THEN
11 IsFound ← TRUE
12 OUTPUT "Surname found at position ", Current
13 ELSE
14 // move to the next list item
15 .....................................................................................................
16 ENDIF
17 UNTIL IsFound = TRUE OR .....................................................................
18 IF IsFound = FALSE
19 THEN
20 OUTPUT "Not Found"
21 ENDIF
22 ENDIF
[6]
...........................................................................................................................................
.......................................................................................................................................[1]
(ii) Write the line number from the pseudocode shown in part (b) that shows the
An array MyList is used to store a sorted data set of non-zero integers. Unused cells contain
zero.
1 2 3 4 5 6 7 8 9 10
MyList 3 5 8 9 13 16 27 0 0 0
(i) Complete the trace table for the dry-run of the pseudocode for the procedure
CALL X(1, 9).
MyList
Index Item 1 2 3 4 5 6 7 8 9 10
1 9 3 5 8 9 13 16 27 0 0 0
[4]
(ii) State the purpose of procedure X when used with the array MyList.
...........................................................................................................................................
.......................................................................................................................................[1]
3 A car hire company hires cars to customers. Each time a car is hired, this is treated as a transaction.
• customer name
• ID number
• car registration
• hire start date
• number of days hired
The transaction data are stored in a text file HIRE-TRANS. The file is made up of a file body,
F_BODY, and a file trailer, F_TRAILER.
(a) The first step in Jackson Structured Programming (JSP) design is to produce a JSP data
structure diagram.
HIRE-TRANS
F_BODY
[7]
© UCLES 2016 9608/41/M/J/16
7
One report is CAR_REPORT. This displays all hire data for all cars.
CAR_REPORT
*
CAR
HIRE_LIST
HIRE
[5]
4 When a car reaches a certain age, a safety assessment has to be carried out. A car’s brakes and
tyres must be tested. The tyre test result and the brakes test result for each car are recorded. If the
car passes the assessment, a safety certificate is issued.
01 car(a05).
02 car(h04).
03 car(a03).
04 car(h07).
05 car(a23).
06 car(p05).
07 car(b04).
08 carRegYear(a05, 2015).
09 carRegYear(h04, 2013).
10 carRegYear(a03, 2008).
11 carRegYear(h07, 2011).
12 carRegYear(a23, 2008).
13 carRegYear(p05, 2014).
14 carRegYear(b04, 2014).
15 testBrakes(h07, pass).
16 testTyres(h07, fail).
17 testBrakes(a03, fail).
18 testTyres(a03, fail).
19 testBrakes(a23, pass).
20 testTyres(a23, pass).
21 carAssessmentDue if carRegYear(Car, RegYear)
and RegYear <= DeadlineYear.
22 issueCertificate(Car) if testTyres(Car, Result) and
testBrakes(Car, Result) and Result = pass.
Identify the car registrations for cars which are due to be tested.
.......................................................................................................................................[1]
(ii) State how clause 22 determines whether or not a safety certificate will be issued.
...........................................................................................................................................
.......................................................................................................................................[1]
retestAllowed(..............................) if ............................................................................
...................................................................................................................................................
...............................................................................................................................................[3]
23 carList = [a03,p05,b04,h04,h07,a23].
A = ......................................................................................
B = ...................................................................................... [2]
C = ..................................................................................... [1]
F = ..................................................................................... [1]
(d) The predicate conCatCompare is defined as a rule and returns TRUE or FALSE as follows:
conCatCompare(X, Y, Z)
Concatenates the lists X and Y and compares the new list with
list Z.
conCatCompare(X, Y, [a7,b6,c4])
If:
X = .................................................................................................................................[1]
5 (a) A program calculates the exam grade awarded from a mark input by the user. The code is
written as a function CalculateGrade.
The function:
Mark Grade
Under 40 FAIL
40 and over and under 55 PASS
55 and over and under 70 MERIT
70 and over DISTINCTION
(ii) State why this table design is suitable for black box testing.
...........................................................................................................................................
.......................................................................................................................................[1]
(b) When designing and writing program code, explain what is meant by:
• an exception
• exception handling
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...............................................................................................................................................[3]
(c) A program is to be written to read a list of exam marks from an existing text file into a 1D array.
Each line of the file stores the mark for one student.
State three exceptions that a programmer should anticipate for this program.
1 ................................................................................................................................................
...................................................................................................................................................
2 ................................................................................................................................................
...................................................................................................................................................
3 ................................................................................................................................................
...............................................................................................................................................[3]
29
30 ENDTRY
First number...53
Second number...6
Arithmetic operation resulted in an overflow
(i) State the pseudocode line number which causes the exception to be raised.
................................................... [1]
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[3]
© UCLES 2016 9608/41/M/J/16 [Turn over
14
6 In a board game, one player has white pieces and the other player has black pieces. Players take
alternate turns to move one of their pieces. White always makes the first move.
• a player is unable to make a move when it is their turn. In this case, there is no winner. This is
called ‘stalemate’.
• a player wins the game as a result of their last move and is called a ‘winner’.
WHITE
WINS
No move
:+,7(·6 possible
TURN
Stalemate
BLACK moves
%/$&.·6 BLACK
TURN WINS
Winning
move
[4]
(b) The layout of the board at the start of the game is shown below:
x
y 1 2 3 4 5 6 7 8
1
8
© UCLES 2016 9608/41/M/J/16
15
The programmer decides to use a 2D array to represent the board. The index numbering to
be used is as shown.
Each square on the board is either occupied by one piece only, or is empty.
The data stored in the array indicate whether or not that square is occupied, and if so, with a
black piece or a white piece.
(i) Write program code to initialise the contents of the array to represent the board at the
start of the game. Use characters as follows for each square:
Visual Basic and Pascal: You should include the declaration statements for variables.
Python: You should show a comment statement for each variable used with its data type.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[4]
© UCLES 2016 9608/41/M/J/16 [Turn over
16
(ii) When a piece is to be moved, a procedure will calculate and output the possible
destination squares for the moving piece.
A piece can move one or more squares, in the x or y direction, from its current position.
For example, for the circled black piece there are nine possible destination squares. Each
of the two destination squares contains a white piece which would be removed.
x
y 1 2 3 4 5 6 7 8
The program requires a procedure ValidMoves.
1
Write program code for procedure ValidMoves with the following procedure header:
Visual Basic and Pascal: You should include the declaration statements for variables.
Python: You should show a comment statement for each variable used with its data type.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
© UCLES 2016 9608/41/M/J/16 [Turn over
18
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[5]
(i) Describe how classes and objects could be used in this problem.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[2]
(ii) For a class you identified in part(c)(i), state two properties and two methods.
Class ..............................................
Properties
1 ........................................................................................................................................
2 ........................................................................................................................................
Methods
1 ........................................................................................................................................
2 ........................................................................................................................................
[2]
Insert coin
locked unlocked
Attempt to
push insert coin
Pass through
start
Mark as follows:
1 mark for both states correct
1 mark for each further label [5]
2 (a) capital_city(santiago).
city_in_country(santiago, chile).
country_in_continent(chile,south_america).
city_visited(santiago).
(b) ThisCity =
manchester
london [2]
(c) countries_visited(ThisCountry)
IF
city_visited(ThisCity) 1
AND 1
city_in_country(ThisCity, ThisCountry) 2 [4]
3 (a)
goods totalling
Y Y Y Y N N N N
more than $20
Conditions
goods totalling
Y Y N N Y Y N N
more than $100
No discount X X X X X
Actions
5% discount X X
10% discount X
1 1 1
1 mark
mark mark mark
[4]
(b)
goods totalling
Y Y Y Y N
more than $20
Conditions
goods totalling
Y Y N N -
more than $100
No discount X X
Actions
5% discount X X
10% discount X
BEGIN
(1) IF GoodsTotal > 20
(1) THEN
(2) IF GoodsTotal > 100
(2) THEN
(3) IF HasDiscountCard = TRUE
(3) THEN
(3) Discount := 10
(3) ELSE
(3) Discount := 5
(2) ELSE
(4) IF HasDiscountCard = TRUE
(4) THEN
(4) Discount := 5
(4) ELSE
(4) Discount := 0
(1) ELSE
(1) Discount := 0;
END;
Example Python
4 (a)
[3]
Mark as follows:
Class header (1 mark)
PUBLIC and PRIVATE used correctly (1 mark)
EmployeeName + EmployeeID (1 mark)
AmountPaidThisMonth (1 mark)
Methods x 3 (1 mark)
Example VB
Class Employee
Private EmployeeName As String
Private EmployeeID As String
Private AmountPaidThisMonth As Decimal
Public Sub SetEmployeeName()
End Sub
Public Sub SetEmployeeID()
End Sub
Public Sub CalculatePay()
End Sub
Example Python
Class Employee():
def __init__(self):
self.__EmployeeName = ""
self.__EmployeeID = ""
self.__AmountPaidThisMonth = 0
def SetEmployeeName(self, Name):
self.__EmployeeName = Name
def SetEmployeeID(self, ID):
self.__EmployeeID = ID
def SetAmountPaidThisMonth(self, Paid):
self.__AmountPaidThisMonth = Paid [max 5]
(ii) AnnualSalary 1
SetSalary 1
CalculatePay : Override 1 [max 2]
(ii) NumberOfItems 10
REPEAT
NoMoreSwaps TRUE
Mark as follows:
• change outer loop to a REPEAT/WHILE loop (1 mark)
• FOR loop has variable used for final value (1 mark)
• Initialise Boolean variable to TRUE (1 mark)
• set Boolean variable to FALSE in correct place (1 mark)
• number of items to consider on each pass decrements (1 mark)
• Correct stopping condition for REPEAT loop (1 mark) [max 5]
6 (a)
Head Ben
Ahmed
Tail Jatinder 0
(b) (i)
Queue
0 [1] 2
[2] 3
TailPointer [3] 4
0 [4] 5
[5] 6
FreePointer [6] 7
1 [7] 8
[8] 9
[9] 10
[10] 0
Mark as follows:
Candidates should use this material in preparation for the examination. Candidates should attempt the
practical programming tasks using their chosen high-level, procedural programming language.
DC (CW/SW) 95225/2
© UCLES 2015 [Turn over
2
This material is intended to be read by teachers and candidates prior to the November 2015 examination
for 9608 Paper 4.
Reminders
The syllabus states:
• there will be questions on the examination paper which do not relate to this pre-release
material
• you must choose a high-level programming language from this list:
ͦ Visual Basic (console mode)
ͦ Python
ͦ Pascal / Delphi (console mode)
The practical skills covered in Paper 2 are a precursor to those required in Paper 4. It is therefore
recommended that the high-level programming language chosen for this paper is the same as that for
Paper 2. This allows for sufficient expertise to be acquired with the opportunity for extensive practice.
TASK 1
The unique registration and the charge (in $) per unit time are stored for all taxis.
Data stored about minibuses also includes an extra charge (in $) per booking and the maximum
number of passengers allowed.
The superclass (also known as base class or parent class) Taxi is designed.
Two subclasses (also known as derived classes or child classes) have been identified:
• Car
• Minibus
Key focus: Object-oriented Programming
TASK 1.1
Complete the inheritance diagram.
TASK 1.2
Complete the class diagram showing the appropriate properties and methods.
.......................................................................
.......................................................................
.......................................................................
.......................................................................
.......................................................................
.......................................................................
.......................................................................
....................................................................... .......................................................................
....................................................................... .......................................................................
....................................................................... .......................................................................
....................................................................... .......................................................................
Constructor() .......................................................................
....................................................................... .......................................................................
....................................................................... .......................................................................
....................................................................... .......................................................................
Note: a constructor is a method that creates a new instance of a class and initialises it.
TASK 1.3
Write program code for the class definitions. Make use of polymorphism and inheritance where
appropriate.
TASK 1.4
Write program code to create a new instance of Car.
TASK 2
A detailed program specification has been written. The program will consist of seven different menu
options handled from a main module by calling seven different procedures. These modules can be
coded independently.
All procedures and the main module are each estimated to take 3 hours to code and 2 hours to test.
TASK 2.1
The project manager initially has one programmer available to write and test the program. The
programmer works 10 hours a day. Calculate how many days it takes before the customer can start
acceptance testing.
TASK 2.2
The customer is not happy about the proposed development time and the project manager considers
hiring extra staff.
One proposal is to deploy one programmer and one software tester to the project.
The project manager needs a PERT chart to calculate the critical path.
1 3 4 5
2
Key focus: Project management
using a PERT chart
Calculate the shortest time (in days) before the client can start acceptance testing.
TASK 2.3
Another proposal is to deploy four programmers, who each carry out their own module testing.
TASK 2.3.1
Draw a GANTT chart for this proposal.
Key focus: Project management using
a GANTT chart
Activity
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Hour number
1
2
3
4
5
6
7
8
9
TASK 2.3.2
If the programmers each work 10 hours a day, calculate how many days it takes before the customer
can start acceptance testing.
TASK 3
• The key field of a book record is the ISBN (a 9-digit string and a check digit).
• Other book data are stored.
• A hashing function is used to calculate a record address.
(The first 3 digits of the ISBN are used as the record address.)
• The random file initially consists of dummy records.
• Dummy records are shown by the ISBN set to 0000000000.
The Hash function assumes the existence of the function LeftToInt, defined below:
TASK 3.1
Write program code to implement the functions LeftToInt and Hash.
TASK 3.2
Write program code to implement the following pseudocode which initialises a random file:
TYPE BookRecord
DECLARE ISBN : STRING[10] // need fixed-length records for
DECLARE Title : STRING[24] // random files
DECLARE OnLoan : BOOLEAN
ENDTYPE
DummyRecord.ISBN ← "0000000000"
TASK 3.3
Write program code to implement the following pseudocode to input 5 book records:
Test your program by inputting book details with ISBNs that will hash to different addresses.
TASK 3.4
You need to test that the records have been saved successfully.
Write program code to read records sequentially from the random file BookFile and output any non-
zero records.
© UCLES 2015 9608/41/PRE/O/N/15
9
TASK 3.5
Key focus: Exception handling
To avoid this, you need to write exception handling code to give an error message instead.
Edit your program code from Task 3.3 to handle the case when "BookFile" does not exist.
TASK 3.6
Add a book record with an ISBN that will cause a collision (also known as a synonym).
Run your program from Task 3.4 again. What do you notice?
TASK 3.7
The pseudocode in Task 3.3 needs amending to handle a collision.
The following algorithm needs to be inserted between line 080 and 090.
Write your Centre number, candidate number and name in the spaces at the top of this page.
Write in dark blue or black pen.
You may use an HB pencil for any diagrams, graphs or rough working.
Do not use staples, paper clips, glue or correction fluid.
DO NOT WRITE IN ANY BARCODES.
At the end of the examination, fasten all your work securely together.
The number of marks is given in brackets [ ] at the end of each question or part question.
DC (CW/SW) 95226/1
© UCLES 2015 [Turn over
2
Throughout the paper you will be asked to write either pseudocode or program code.
Complete the statement to indicate which high-level programming language you will use.
1 A large software house has been asked to supply a computerised solution for a business. The
project manager has drawn up a list of activities and their likely duration.
Weeks to
Activity Description
complete
A Write requirement specification 5
B Produce program design 5
C Write module code 15
D Module testing 10
E Integration testing 5
F Alpha testing 3
G Install software and acceptance testing 5
H Write end user training guide 5
J Write technical documentation 10
K End user training 4
L Sign off final system 1
(a) The project manager decides to construct a Program Evaluation Review Technique (PERT)
chart from this data.
1 5 2 3 5 6 3 7 9
A F
10
J
4 8
10
.......................................................................................................................................[2]
(iii) Calculate the minimum number of weeks for the completion of this solution.
.......................................................................................................................................[1]
(c) Give a reason why the project manager used a PERT chart.
...................................................................................................................................................
...............................................................................................................................................[1]
2 A declarative programming language is used to represent the following facts and rules:
01 male(ali).
02 male(raul).
03 male(ahmed).
04 male(philippe).
05 female(meena).
06 female(aisha).
07 female(gina).
08 parent(ali, raul).
09 parent(meena, raul).
10 parent(ali, ahmed).
11 parent(meena, ahmed).
12 parent(ali, aisha).
13 parent(meena, aisha).
14 father(A, B) IF male(A) AND parent(A, B).
Clause Explanation
01 Ali is male
05 Meena is female
08 Ali is a parent of Raul
14 A is the father of B if A is male and A is a parent of B
15 ..........................................................................................................................................
16 ......................................................................................................................................[2]
parent(P, raul)
returns
P = ali, meena
parent(ali, C)
C = ......................................................................................................................................[2]
(c) Use the variable F to write the goal to find the father of Ahmed.
...............................................................................................................................................[1]
mother(X, Y)
IF .............................................................................................................................................
.............................................................................................................................................. [2]
grandparent(W, Z)
IF .............................................................................................................................................
...................................................................................................................................................
...............................................................................................................................................[2]
grandfather(G, K)
IF .............................................................................................................................................
...................................................................................................................................................
...............................................................................................................................................[2]
3 A lending library stocks two types of item for loan: books and CDs.
All stock items have a title, the date the item was acquired and whether the item is currently out on
loan.
Books have an author and ISBN. CDs have an artist and play time in minutes.
The library needs a program to process data about the stock items. The program will use an
object-oriented programming language.
(a) Complete the class diagram showing the appropriate properties and methods.
StockItem
Title: STRING
......................................................................
......................................................................
......................................................................
ShowTitle()
......................................................................
......................................................................
......................................................................
Book CD
...................................................................... ......................................................................
...................................................................... ......................................................................
...................................................................... ......................................................................
Constructor() ......................................................................
ShowAuthor() ......................................................................
...................................................................... ......................................................................
...................................................................... ......................................................................
[7]
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[3]
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[3]
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[3]
4 A binary tree Abstract Data Type (ADT) has these associated operations:
(a) Show the final state of the binary tree after the following operations are carried out.
CreateTree
Add("Dodi")
Add("Farai")
Add("Elli")
Add("George")
Add("Ben")
Add("Celine")
Add("Ali")
[4]
(b) The binary tree ADT is to be implemented as an array of nodes. Each node consists of data
and two pointers.
TYPE Node
DECLARE Name : STRING
DECLARE LeftPointer : INTEGER
DECLARE RightPointer : INTEGER
ENDTYPE
The statement
The CreateTree operation links all nodes into a linked list of free nodes. It also initialises the
RootPointer and FreePointer.
Show the contents of the Tree array and the values of the two pointers, RootPointer and
FreePointer, after the operations given in part (a) have been carried out.
Tree
RootPointer Name LeftPointer RightPointer
[1]
[2]
FreePointer [3]
[4]
[5]
[6]
[7]
[8]
[9]
[10]
[7]
(c) A programmer needs an algorithm for outputting items in ascending order. To design this, the
programmer writes a recursive procedure in pseudocode.
02 IF Tree[Root].LeftPointer .................................................................
03 THEN
04 TraverseTree( .............................................................................)
05 ENDIF
07 IF ........................................................................................................ <> 0
08 THEN
09 TraverseTree( .............................................................................)
10 ENDIF
11 ENDPROCEDURE
[5]
(ii) Explain what is meant by a recursive procedure. Give a line number from the code above
that shows procedure TraverseTree is recursive.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
(iii) Write the pseudocode call required to output all names stored in Tree.
...........................................................................................................................................
.......................................................................................................................................[1]
5 Data about sports club members are stored in a random file of records.
• The key field of a member record is the member ID (range 1000 to 9999).
• Other member data are stored.
• A hashing function is used to calculate a record address.
• The random file initially consists of dummy records.
• Dummy records are shown by member ID set to 0.
RETURN Address
ENDFUNCTION
(a) New members with the following member IDs have joined the sports club:
Indicate where each record should be stored by deleting the zero and writing the member ID
in the correct cell.
MembershipFile
Address MemberID Other member data
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
96 0
97 0
98 0
99 0 [2]
(b) (i) The program stores a new member’s data in the record variable NewMember. The field
MemberID stores the member ID.
20 NewAddress ← ..........................................................................................................
40 SEEK ...........................................................................................................................
(ii) Before records can be saved to the file MembershipFile, the file needs to be opened.
01 TRY
03 EXCEPT
04 ..............................................................................................................................
05 ENDTRY
[2]
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[2]
(iv) Describe a method, without changing the function Hash, to handle the problem identified
in part (b)(iii).
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[2]
(v) Write pseudocode to implement the method you described in part (b)(iv).
Choose line numbers to indicate where your pseudocode should be inserted in the
pseudocode of part (b)(i).
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[4]
Permission to reproduce items where third-party owned material protected by copyright is included has been sought and cleared where possible. Every reasonable
effort has been made by the publisher (UCLES) to trace copyright holders, but if any items requiring clearance have unwittingly been included, the publisher will
be pleased to make amends at the earliest possible opportunity.
To avoid the issue of disclosure of answer-related information to candidates, all copyright acknowledgements are reproduced online in the Cambridge International
Examinations Copyright Acknowledgements Booklet. This is produced for each series of examinations and is freely available to download at www.cie.org.uk after
the live examination series.
Cambridge International Examinations is part of the Cambridge Assessment Group. Cambridge Assessment is the brand name of University of Cambridge Local
Examinations Syndicate (UCLES), which is itself a department of the University of Cambridge.
1 (a) (i)
5 5 15 5 3 5
A B C E F G
[max. 7]
(ii) 1 – 2 – 3 – 5 – 6 – 7 – 9 – 8 – 10
1–5 scores 1
6–10 scores 1 [2]
(d) mother(X, Y)
IF
female(X) AND parent(X, Y). [2]
(e) grandparent(W, Z)
IF
parent(W,X)
AND parent(X,Z). [2]
(f) grandfather(G, K)
IF
male(G) AND
grandparent(G, K).
alternative:
father(G, X) AND
parent(X, K). [2]
3 (a)
StockItem
Title: STRING
DateAcquired : TDATETIME………………………
OnLoan: BOOLEAN .………………………………………
………………………………………………………………………………………
ShowTitle()
ShowDateAcquired() ……………………………………
ShowOnLoan() …………………………………………………
………………………………………………………………………………………
Book CD
Author: STRING Artist: STRING ……………………………………………
ISBN: STRING………………………………………… Playtime: INTEGER ……………………………………
……………………………………………………………………………………… ………………………………………………………………………………………
……………………………………………………………………………………… ………………………………………………………………………………………
Constructor() Constructor()…………………………………………………
ShowAuthor() ShowArtist() …………………………………………………
ShowISBN()………………………………………………………… ShowPlayTime() ……………………………………………
……………………………………………………………………………………… ………………………………………………………………………………………
[max. 7]
Pascal
StockItem = CLASS
PUBLIC
Procedure ShowTitle();
Procedure ShowDateAcquired();
Procedure ShowOnLoan();
PRIVATE
Title : STRING;
DateAcquired : TDateTime;
OnLoan : Boolean;
END;
Python
class StockItem :
def __int__(self) :
self.__Title = ""
self.__DateAquired = ""
self.__OnLoan = False
def ShowTitle() :
pass
def ShowDateAcquired() :
pass
def ShowOnLoan() :
pass
VB.NET
Class StockItem
Public Sub ShowTitle()
End Sub
Public Sub ShowDateAquired()
End Sub
Public Sub ShowOnLoan()
End Sub
Private Title As String
Private DateAquired As Date
End Class [3]
Pascal
Python
class Book(StockItem) :
def __init__(self) :
self.__Author = ""
self.__ISBN = ""
def ShowAuthor() :
pass
def ShowISBN() :
pass
VB.NET
(iii) Pascal
NewBook := Book.Create; 1
NewBook.Title := 'Computers';
NewBook.Author := 'A.Nyone';
NewBook.ISBN := '099111'; 1
NewBook.DateAcquired := '12/11/2001';
NewBook.OnLoan := FALSE 1
Python
NewBook = Book() 1
NewBook.Title = "Computers"
NewBook.Author = "A.Nyone"
NewBook.ISBN = "099111" 1
NewBook.DateAcquired = "12/11/2001"
NewBook.OnLoan = False 1
VB.NET
4 (a)
[4]
(b)
Tree
[2] Farai 3 4
[5] Ben 7 6
[6] Celine 0 0
[7] Ali 0 0
[8] 9 0
[9] 10 0
[10] 0 0
[7]
5 (a)
MembershipFile
0 0
1 1001
2 7002
3 0
4 0
5 3005
6 0
7 0
8 0
: :
: :
96 4096
97 0
98 2098
99 0
(ii) 01 TRY
02 OPENFILE "MembershipFile" FOR RANDOM
03 EXCEPT
04 OUTPUT "File does not exist"
05 ENDTRY [2]
(iii) collisions/synonyms
The previous record will be overwritten [2]
Candidates should use this material in preparation for the examination. Candidates should attempt the
practical programming tasks using their chosen high-level, procedural programming language.
DC (NH/SG) 106700/5
© UCLES 2016 [Turn over
2
This material is intended to be read by teachers and candidates prior to the June 2016 examination for
9608 Paper 4.
Candidates will also benefit from using pre-release materials from previous examinations. These are
available on the teacher support site.
Reminders
The syllabus states:
• there will be questions on the examination paper which do not relate to this pre-release material
• you must choose a high-level programming language from this list:
• Visual Basic (console mode)
• Python
• Pascal / Delphi (console mode)
Note: A mark of zero will be awarded if a programming language other than those listed is used.
The practical skills covered in Paper 2 are a precursor to those required in Paper 4. It is therefore
recommended that the high-level programming language chosen for this paper is the same as that for
Paper 2. This allows for sufficient expertise to be acquired with the opportunity for extensive practice.
Declaration of variables
The syllabus document shows the syntax expected for a declaration statement in pseudocode.
It is appreciated that candidates who use Python as their chosen language will not be familiar with the
concept of declaring all variables with their data type before they are used.
However, answers using Python will be required, instead of a declaration statement, to include a
comment statement, documenting the identifier name with its intended data type.
The question will clarify this with a wording and answer layout such as:
Visual Basic and Pascal: You should include declaration statements for variables.
Python: You should show a comment statement for each variable used with its data type.
..........................................................................................................................................
..........................................................................................................................................
An algorithm written in pseudocode requires that all variables have been identified. This may not be
the case if the initial attempt at the algorithm design is in structured English. The candidate will then be
required to identify the variables from the question.
A JSP data structure diagram is used to represent the data used by a problem.
Task 1
1.1 This symbol is used in a JSP data structure diagram. What is it used to represent?
A B C
1.3 Which are the three true statements for the JSP data structure diagram shown below?
A B C
1.5 This symbol is used in a JSP data structure diagram. What is it used to represent?
• sequence
• selection
• a procedure
• iteration
Task 2
A train, Train, consists of an engine, Engine, followed by a carriage, Carriage. Sometimes there is
a second Engine at the rear of the train.
Task 4
4.1 This symbol is used in a JSP data structure diagram. What is it used to represent?
4.2 A Train consists of an Engine followed by one or more Carriages. Sometimes there is a
second Engine at the rear of the train.
Key focus:
Draw the JSP data structure diagram. Using ‘iteration’ …
4.3 An examination paper, ExamPaper, consists of a front page, Front, followed by at least one
question, Question.
Task 5
A shipping company has a number of merchant ships. Data are recorded for all the voyages made by
each ship.
• a file header, FileHeader, which shows the date the file was last updated
• a file body, FileBody, which contains data for all the ships
• a file trailer, FileTrailer, which marks the end of the file
The data for each ship are made up of the name of the ship followed by the data records for each
voyage made. There may be a ship record for a ship which has not made any voyages so far.
ShipFile 1
*
Ship 3
*
ShipName ShipVoyage 4
2 the file is made up of the sequence of data components stated in the bulleted list above the
diagram.
Note:
• A component which has no derived lower level component(s) is called an elementary component.
FileHeader and FileTrailer are both elementary components.
• It may have been tempting to have the iterated data item Ship one line above (which would seem
to avoid the use of the FileBody item. However, this would have resulted in a sequence of ‘mixed-
type components’ at the same level. This must always be avoided.
3 The component Ship is an iteration, as it consists of the data for several ships.
4 We have ‘mixed-type components’ at the same level. That is ShipName (elementary) and
ShipVoyage (iterated). The solution therefore is the same as earlier. This gives the final diagram
below:
ShipFile
*
Ship
ShipName ShipBody
*
ShipVoyage
Key focus:
A data structure
Task 6 diagram for output
A JSP data structure diagram can also be used to describe the data requirements for a printed report.
A report, Report, is made up of a number of pages, Page. Each page consists of a possible heading,
Heading, followed by a number of lines, Line.
Logic Programming
Key focus:
Task 7 Lists
Logic programming can use a data structure called a list. The list items are enclosed inside square
brackets. Each item is separated by a comma. The list can be given an identifier name.
[budapest,paris,london,singapore,dhaka,oslo,brussels,amsterdam,cairo]
Example:
• X = budapest
• Y = [paris,london,singapore,dhaka,oslo,brussels,amsterdam,cairo]
Note:
The head is always a list item
The tail is always a list
Predicates can be defined and used to manipulate and interrogate a list.
Assume the predicate isEmpty is defined in the knowledge base to return TRUE or FALSE.
Example:
7.1
A = ......................................................................................
B = ......................................................................................
7.2
[kingston,rome,riga|C] = [kingston,rome,riga,bangkok,minsk]
C = ......................................................................................
7.3
[suva,stanley] = [D,E|F]
F = ......................................................................................
removeAndCompare(A,B,C)
Remove any elements from list A which are also present in list B.
Compare the amended list A with list C.
If the lists are identical, the predicate returns TRUE, otherwise returns FALSE.
7.4.1
removeAndCompare([moscow,ottowa,monaco],
[monaco,london],
[moscow,ottowa,monaco])
What is returned by this predicate?
......................................................................................
7.4.2
removeAndCompare([orange,banana],[ ],[orange,banana])
......................................................................................
Write your Centre number, candidate number and name in the spaces at the top of this page.
Write in dark blue or black pen.
You may use an HB pencil for any diagrams, graphs or rough working.
Do not use staples, paper clips, glue or correction fluid.
DO NOT WRITE IN ANY BARCODES.
At the end of the examination, fasten all your work securely together.
The number of marks is given in brackets [ ] at the end of each question or part question.
DC (LEG/SW) 95224/2
© UCLES 2015 [Turn over
2
Throughout the paper you will be asked to write either pseudocode or program code.
Complete the statement to indicate which high-level programming language you will use.
1 A turnstile is a gate which is in a locked state. To open it and pass through, a customer inserts
a coin into a slot on the turnstile. The turnstile then unlocks and allows the customer to push the
turnstile and pass through the gate.
After the customer has passed through, the turnstile locks again. If a customer pushes the turnstile
while it is in the locked state, it will remain locked until another coin is inserted.
The turnstile has two possible states: locked and unlocked. The transition from one state to
another is as shown in the table below.
..............................
.............................. ..............................
.............................. ..............................
start ..............................
[5]
2 A declarative programming language is used to represent the knowledge base shown below:
01 capital_city(amman).
02 capital_city(beijing).
03 capital_city(brussels).
04 capital_city(cairo).
05 capital_city(london).
06 city_in_country(amman, jordan).
07 city_in_country(shanghai, china).
08 city_in_country(brussels, belgium).
09 city_in_country(london, uk).
10 city_in_country(manchester, uk).
11 country_in_continent(belgium, europe).
12 country_in_continent(china, asia).
13 country_in_continent(uk, europe).
14 city_visited(amman).
15 city_visited(beijing).
16 city_visited(cairo).
Clause Explanation
01 Amman is a capital city
06 Amman is a city in the country of Jordan
11 Belgium is a country in the continent of Europe
14 The travel writer visited Amman
The travel writer visited the city of Santiago which is the capital city of Chile, in the continent
of South America.
17 ............................................................................................................................................
...................................................................................................................................................
18 ............................................................................................................................................
...................................................................................................................................................
19 ............................................................................................................................................
...................................................................................................................................................
20 ............................................................................................................................................
.............................................................................................................................................. [4]
country_in_continent(ThisCountry, europe)
returns
ThisCountry = belgium, uk
city_in_country(ThisCity, uk)
ThisCity = ...........................................................................................................................
.............................................................................................................................................. [2]
(c) Complete the rule below to list the countries the travel writer has visited.
countries_visited(ThisCountry)
IF .............................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [4]
3 A shop gives some customers a discount on goods totalling more than $20.
The discounts are:
• 5% for goods totalling more than $100
• 5% with a discount card
• 10% with a discount card and goods totalling more than $100
goods totalling
Y Y Y Y N N N N
more than $20
Conditions
goods totalling
Y Y N N Y Y N N
more than $100
No discount
Actions
5% discount
10% discount
[4]
goods totalling
more than $20
Conditions
goods totalling
more than $100
No discount
Actions
5% discount
10% discount
[5]
(c) The simplified table produced in part (b) is used as a design for program code.
The following identifier table shows the parameters to be passed to the function Discount.
This function returns the discount amount as an integer.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [6]
[3]
• methods
• SetEmployeeName
• SetEmployeeID
• CalculatePay
Write program code for the class definition of the superclass Employee.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [5]
© UCLES 2015 9608/41/M/J/15
9
(c) (i) State the properties and/or methods required for the subclass HourlyPaidEmployee.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [4]
(ii) State the properties and/or methods required for the subclass SalariedEmployee.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [2]
(d) Name the feature of object-oriented program design that allows the method CalculatePay
to be declared in the superclass Employee.
...................................................................................................................................................
.............................................................................................................................................. [1]
(ii) A special case is when NameList is already in order. The algorithm in part (a)(i) is
applied to this special case.
Explain how many iterations are carried out for each of the loops.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [3]
FOR ThisPointer ← 1 TO 9
FOR Pointer ← 1 TO 9
IF NameList[Pointer] > NameList[Pointer + 1]
THEN
Temp ← NameList[Pointer]
NameList[Pointer] ← NameList[Pointer + 1]
NameList[Pointer + 1] ← Temp
ENDIF
ENDFOR
ENDFOR
(i) As in part (a)(ii), a special case is when NameList is already in order. The algorithm in
part (b) is applied to this special case.
Explain how many iterations are carried out for each of the loops.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [2]
(ii) Rewrite the algorithm in part (b), using pseudocode, to reduce the number of
unnecessary comparisons. Use the same variable names where appropriate.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [5]
• create queue
• add item to queue
• remove item from queue
CreateQueue
AddName("Ali")
AddName("Jack")
AddName("Ben")
AddName("Ahmed")
RemoveName
AddName("Jatinder")
RemoveName
Add appropriate labels to the diagram to show the final state of the queue. Use the space on
the left as a workspace. Show your final answer in the node shapes on the right:
[3]
TYPE Node
DECLARE Name : STRING
DECLARE Pointer : INTEGER
ENDTYPE
The statement
(i) The CreateQueue operation links all nodes and initialises the three pointers that need
to be used: HeadPointer, TailPointer and FreePointer.
Complete the diagram to show the value of all pointers after CreateQueue has been
executed.
Queue
HeadPointer Name Pointer
[1]
[2]
TailPointer [3]
[4]
[5]
FreePointer [6]
[7]
[8]
[9]
[10]
[4]
(ii) The algorithm for adding a name to the queue is written, using pseudocode, as a
procedure with the header:
PROCEDURE AddName(NewName)
Complete the pseudocode for the procedure RemoveName. Use the variables listed in
the identifier table.
PROCEDURE RemoveName()
// Report error if Queue is empty
...........................................................................................................................
...........................................................................................................................
...........................................................................................................................
...........................................................................................................................
OUTPUT Queue[…………………………………………………………].Name
// current node is head of queue
...........................................................................................................................
// update head pointer
...........................................................................................................................
// if only one element in queue then update tail pointer
...........................................................................................................................
...........................................................................................................................
...........................................................................................................................
...........................................................................................................................
// link released node to free list
...........................................................................................................................
...........................................................................................................................
...........................................................................................................................
ENDPROCEDURE
[6]
Permission to reproduce items where third-party owned material protected by copyright is included has been sought and cleared where possible. Every reasonable
effort has been made by the publisher (UCLES) to trace copyright holders, but if any items requiring clearance have unwittingly been included, the publisher will
be pleased to make amends at the earliest possible opportunity.
To avoid the issue of disclosure of answer-related information to candidates, all copyright acknowledgements are reproduced online in the Cambridge International
Examinations Copyright Acknowledgements Booklet. This is produced for each series of examinations and is freely available to download at www.cie.org.uk after
the live examination series.
Cambridge International Examinations is part of the Cambridge Assessment Group. Cambridge Assessment is the brand name of University of Cambridge Local
Examinations Syndicate (UCLES), which is itself a department of the University of Cambridge.
Q estio
Qu on A
An
nsw
werr Mark
ks
1 (a)) (i)
( TY
YPE
E Lin
L nk
ked
dLi
ist
t 1 3
(D
DEC
CLA
ARE
E) S
Sur
rna
ame
e : ST
TRIING
G 1
(D
DEC
CLA
ARE
E) P
Ptr I TE
r : IN EGE
ER
EN
NDT
TYP
PE 1
cce
Ac eptt:
Li
ink
ked
dList : RE
ECO
ORD 1
Su
urn me : S
nam STR
RIN
NG 1
tr : IN
Pt NTEG
GER
R
EN
NDR
REC
COR
RD
D 1
cce
Ac eptt:
TY
YPE
E Lin
L nkked
dLi t = RE
ist ECO
ORD
D 1
Su
urn
nam
me : S
STR
RIN
NG 1
tr : IN
Pt NTEG
GER
R
EN
NDT
TYP
PE / E
END
DRE
ECO
ORD 1
cce
Ac eptt:
ST
TRU
UCT
TUR RE L
Lin
nke
edL
List
t 1
(D
DEC
CLA
ARE
E) S
Sur
rna
ame
e : ST
TRIING
G 1
(D
DEC
CLA
ARE
E) P
Ptr I TE
r : IN EGE
ER
EN
NDS RUCTUR
STR RE 1
Accce
ept AS OF in
S / O nste
ead o
of :
(iii) (D
DEC
CLA E) S
ARE Sur
rna
ame
eLis
st[
[1:
:50
000
0] : Lin
L nke
edL
List
t 2
Accce
ept AS
S / O OF innsteead o
of :
Accce
ept () instteaad of []
Accce
ept witho
outt lowe
er bou
b undd
Ind
dexx sep
s para
ato
or can
c n bee , : ...
(b)) (i)
( Wu
u 1
Accce
ept with quote
es
(iii) 6 1
(c)) (i)
( Is
sFo nd + relevantt descrip
oun ptio
on 1 2
BO
OOL
LEA
AN 1
© Ca
amb
brid
dge
e In
nterrnattion
nal Ex
xam
mina
atio
ons
s 20
016
6
Page 3 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2016 9608 41
2 (a) (i) A procedure which is defined in terms of itself // A procedure which makes a call to 1
itself // A procedure that calls itself
(ii) 08 // 8 1
1 9 3 5 8 9 13 16 27 0 0 0
13
4
5 16
6 27
7 0
3 (a) 7
HIRE-TRANS
F_BODY F_TRAILER
TRANS
Customer
data Hire data
Mark as follows:
Label F_TRAILER 1
Label TRANS 1
(b) 5
Mark as follows:
Selection symbol x 2 (Car-hire / No car-hire) 1
Labelling for CAR_HIRE / NO_HIRE (accept similar labels*) 1
Labelling for Car registration and Car total / Total hires 1
Iteration symbol for HIRE (accept in HIRE_LIST as a BOD) 1
Labelling for start date and number of days (as per diagram) 1
(ii) The car must pass (both) brake test and tyres test 1
(b) retestAllowed(ThisCar) 3
1
If (testBrakes(ThisCar, pass) and testTyres(ThisCar, fail))
1
or (testBrakes(ThisCar, fail) and testTyres(ThisCar, pass))
1
(one mark per bold underlined all correct)
accept another variable instead of ThisCar, but must be same throughout.
must be []
must be lower case, but don’t penalise twice, so follow through from part(b)
(ii) [p05,m04] 1
(iii) [ ] 1
(d) [ ] 1
Normal FAIL/PASS/MERIT/DISTINCTION
Abnormal Error
Extreme/Boundary FAIL/PASS/MERIT/DISTINCTION
(ii) (The programmer is) concerned only with the input (i.e. the mark) to the function and 1
monitoring the expected output (i.e. the grade)
// can compare expected result and actual result
(b) Exception: 3
1. situation causing a crash / run-time error / fatal error 1
Exception handling:
2. code which is called when a run-time error occurs 1
3. … to avoid the program terminating/crashing 1
(d) (i) 09 // 9 1
6 (a) 4
BOARD class:
Properties:
• Number of squares / size / dimensions
• Current state of all squares
Methods: –
• Set the starting board
• Capture the finishing state of the board
• Display the state of the board after each move
PIECE class:
Properties:
• Starting x position
• Starting y position
• Current x position
• current y position
• Colour
• State / Removed / Active
Methods:
• Move piece
• Remove piece
Mark as follows:
two correct responses are worth 1 mark
Programming code
6 (b) (i)
VB.NET
Dim Board(8, 8) As Char
Dim Row, Column As Integer
For Row = 1 To 2
For Column = 1 To 8
Board(Row, Column) = "B"
Next
Next
For Row = 3 To 6
For Column = 1 To 8
Board(Row, Column) = "E"
Next
Next
For Row = 7 To 8
For Column = 1 To 8
Board(Row, Column) = "W"
Next
Next
PASCAL
var Row, Column : integer;
Board : array[1..8, 1..8] of char;
begin
for Row := 1 to 2 do
for Column := 1 to 8 do
Board[Row, Column] := 'B';
for Row := 3 to 6 do
for Column := 1 to 8 do
Board[Row, Column] := 'E';
for Row := 7 to 8 do
for Column := 1 to 8 do
Board[Row, Column] := 'W';
end.
PYTHON
Board = [["" for j in range(9)] for i in range(9)]
for Row in range(1, 3) :
for Column in range(1, 9) :
Board[Row][Column] = "B"
for Row in range(3, 7) :
for Column in range(1, 9) :
Board[Row][Column] = "E"
for Row in range(7, 9) :
for Column in range(1, 9) :
Board[Row][Column] = "W"
Board = [[]]
for i in range(9) :
for j in range(9) :
Board.append("")
Instead of initialising with empty string, could initialise with ‘E’. this would then only require ‘B’ and ‘W’
loops later.
For example:
Board =[]
for i in range(9):
Board.append(["E"]*9)
6 (b) (ii)
VB.NET
Sub ValidMoves(ByVal PieceColour As Char, ByVal xCurrent As Integer,
ByVal yCurrent As Integer)
Dim i As Integer
Dim StopperColour As Char
Dim NoFurther As Boolean
If PieceColour = "B" Then
StopperColour = "W"
Else
StopperColour = "B"
End If
Console.WriteLine("Possible moves are : ")
If xCurrent <> 1 Then
Console.WriteLine("Moving LEFT . . .")
i = xCurrent – 1
NoFurther = False
do
if Board(i, yCurrent) = "E" Then
Console.WriteLine(i & " " & yCurrent)
End If
if Board(i, yCurrent) = StopperColour Then
Console.WriteLine(i & " " & yCurrent & " REMOVE PIECE")
NoFurther = True
End If
i = i – 1
Loop Until i = 0 Or NoFurther = True
End If
if xCurrent <> 8 Then
Console.WriteLine("Moving RIGHT . . .")
i = xCurrent + 1
NoFurther = False
do
if Board(i, yCurrent) = "E" :
Console.WriteLine(i & " " & yCurrent)
End If
if Board(i, yCurrent) = StopperColour Then
Console.WriteLine(i & " " & yCurrent & " REMOVE PIECE")
NoFurther = True
End If
i = i + 1
Loop Until i = 9 Or NoFurther = True
End If
End Sub
PASCAL
procedure ValidMoves(PieceColour : char; xCurrent, yCurrent : integer);
var StopperColour : char;
i : integer;
NoFurther : boolean;
begin
if (PieceColour = 'B') then
StopperColour := 'W'
else
StopperColour := 'B';
writeln('Possible moves are : ');
if (xCurrent <> 1) then
begin
writeln('Moving LEFT . . . ');
i := xCurrent – 1;
NoFurther := false;
repeat
if (Board[i, yCurrent] = 'E') then
writeln(intToStr(i) + ' ' + intToStr(yCurrent));
if (Board[i, yCurrent] = StopperColour) then
begin
writeln(intToStr(i) + ' ' + intToStr(yCurrent) + ' REMOVE
PIECE');
NoFurther := true;
end;
i := i – 1;
until ((i = 0) or (NoFurther = true));
end;
if (xCurrent <> 8) then
begin
writeln('Moving RIGHT . . . ');
i := xCurrent + 1;
NoFurther := false;
repeat
if (Board[i, yCurrent] = 'E') then
writeln(intToStr(i) + ' ' + intToStr(yCurrent));
if (Board[i, yCurrent] = StopperColour) then
begin
writeln(intToStr(i) + ' ' + intToStr(yCurrent) + ' REMOVE
PIECE');
NoFurther := true;
end;
i := i + 1;
until ((i = 9) or (NoFurther = true));
end;
end;
PYTHON
at the Centre.
Candidates should use this material in preparation for the examination. Candidates should attempt the
practical programming tasks using their chosen high-level, procedural programming language.
DC (ST) 115878/4
© UCLES 2016 [Turn over
2
Teachers and candidates should read this material prior to the November 2016 examination for
9608 Paper 4.
Reminders
The syllabus states:
• there will be questions on the examination paper which do not relate to this pre-release material
• you must choose a high-level programming language from this list:
• Visual Basic (console mode)
• Python
• Pascal / Delphi (console mode)
Note: A mark of zero will be awarded if a programming language other than those listed is used.
The practical skills for Paper 4 build on the practical skills for Paper 2. We therefore recommend that
candidates choose the same high-level programming language for this paper as they did for Paper 2.
This will give candidates the opportunity for extensive practice and allow them to acquire sufficient
expertise.
Declaration of variables
The syllabus document shows the syntax expected for a declaration statement in pseudocode.
If Python is the chosen language, each variable’s identifier (name) and its intended data type must be
documented using a comment statement.
TASK 1
When writing high-level language programs you are asked to use one of:
• Python
• Visual Basic (console mode)
• Pascal/Delphi (console mode) Key focus: Programming environments
Make sure you know the name of the programming environment that you use to write programs in your
chosen programming language.
TASK 1.1
Explore the features of your editor that help you to write program code.
When and how does your programming environment report syntax errors?
TASK 1.2
When you write program code, explore debugger features available to you and practise using them to
step through programs and explore the state of the variables after each instruction.
Explore how the debugger can help to find logic errors and run-time errors.
TASK 1.3
You will need to write a main program that initialises and populates an array of names to be sorted.
The program then calls the procedure Sort.
Decide on some test data. Write down the expected results after each repetition (iteration) of the FOR
loop. You should test your program with several different sets of data. Use the debugger each time to
step through the program.
Extension task
Explore what program libraries are available for your chosen programming language. How can you
make use of a library routine that is not part of the basic set-up of your programming environment?
TASK 2
The table shows part of the instruction set for a processor which has one general purpose register, the
Accumulator (ACC), and an index register (IX).
Note: These instructions are all referred to in syllabus sections 1.4.3 and 3.6.2.
Instruction
Op Explanation
Operand
code
LDM #n Immediate addressing. Load the number n to ACC
LDD <address> Direct addressing. Load the contents of the given address to ACC
Indirect addressing. The address to be used is at the given address. Load the
LDI <address>
contents of this second address to ACC
Indexed addressing. Form the address from <address> + the contents of the
LDX <address>
index register. Copy the contents of this calculated address to ACC
LDR #n Immediate addressing. Load the number n into IX
STO <address> Store the contents of ACC at the given address
ADD <address> Add the contents of the given address to the ACC
INC <register> Add 1 to the contents of the register (ACC or IX)
DEC <register> Subtract 1 from the contents of the register (ACC or IX)
JMP <address> Jump to the given address
CMP <address> Compare the contents of ACC with the contents of <address>
CMP #n Compare the contents of ACC with number n
JPE <address> Following a compare instruction, jump to <address> if the compare was TRUE
JPN <address> Following a compare instruction, jump to <address> if the compare was FALSE
AND #n Bitwise AND operation of the contents of ACC with the operand
AND <address> Bitwise AND operation of the contents of ACC with the contents of <address>
XOR #n Bitwise XOR operation of the contents of ACC with the operand
XOR <address> Bitwise XOR operation of the contents of ACC with the contents of <address>
OR #n Bitwise OR operation of the contents of ACC with the operand
OR <address> Bitwise OR operation of the contents of ACC with the contents of <address>
IN Key in a character and store its ASCII value in ACC
OUT Output to the screen the character whose ASCII value is stored in ACC
END Return control to the operating system
Notes:
Tasks 2.1 to 2.7 all use one of the following two formats for symbolic addressing.
Format Example
<label>: <op code> <operand> START: LDA #0
<label>: <data> NUM1: B01001010
Write assembly language program code using the instruction set provided on page 4.
TASK 2.1
X ← A + B
END
Instruction
Label Op Comment
Operand
code
START: // load the content of A into ACC
X:
A: 5
B: 3
TASK 2.2
IF X = A
THEN
OUTPUT CHR(X) // statements for THEN part
ELSE
A ←
A + 1 // statements for ELSE part
ENDIF
END
Instruction
Label Op Comment
Operand
code
START: // load the content of X into ACC
A: 65
X: 67
Note: the built-in function CHR(X) returns the character that is represented by the ASCII code held in X.
TASK 2.3
REPEAT
OUTPUT CHR(X)
X ← X - 1
UNTIL X = A
END
Instruction
Label Op Comment
Operand
code
LOOP: // instructions to be repeated start here
X: 90
A: 65
TASK 2.4
FOR COUNT ←
1 TO 4
OUTPUT CHARS[COUNT]
ENDFOR
END
Instruction
Label Op Comment
Operand
code
// set ACC to zero
// COUNT = 4 ?
COUNT:
CHARS: 72 // 'H'
69 // 'E'
76 // 'L'
80 // 'P'
TASK 2.5
WHILE X <> B
OUTPUT CHARS[B]
B ← B + 1
ENDWHILE
END
Instruction
Label Op Comment
Operand
code
LOOP: // load content of X into ACC
// is content of ACC = content of B ?
// if equal (TRUE) jump to ENDWHILE
// instructions to be repeated start here
X: 4
B: 0
CHARS: 72 // 'H'
69 // 'E'
76 // 'L'
80 // 'P'
TASK 2.6
Instruction
Address Op Comment
Operand
code
// use indirect addressing to load contents of
LOOP:
address found at address 100
// output character with ASCII code held in ACC
// increment ACC
100 102
101
102 77 // 'M'
103 65 // 'A'
104 84 // 'T'
105 72 // 'H'
106 83 // 'S'
107
TASK 2.7
Programmers use bitwise operations (AND, OR, XOR) to set or examine specific bits.
Example:
Instruction
Label Op Comment
Operand
code
LOOP: LDD X // load content of X into ACC
// bitwise AND operation on content of ACC and
AND MASK
content of MASK
STO Y // store content of ACC in Y
X: B10101111
MASK: B00000001
Write simple programs using the different bitwise operations (AND, OR, XOR) and different MASK content.
Permission to reproduce items where third-party owned material protected by copyright is included has been sought and cleared where possible. Every reasonable
effort has been made by the publisher (UCLES) to trace copyright holders, but if any items requiring clearance have unwittingly been included, the publisher will
be pleased to make amends at the earliest possible opportunity.
To avoid the issue of disclosure of answer-related information to candidates, all copyright acknowledgements are reproduced online in the Cambridge International
Examinations Copyright Acknowledgements Booklet. This is produced for each series of examinations and is freely available to download at www.cie.org.uk after
the live examination series.
Cambridge International Examinations is part of the Cambridge Assessment Group. Cambridge Assessment is the brand name of University of Cambridge Local
Examinations Syndicate (UCLES), which is itself a department of the University of Cambridge.
Write your Centre number, candidate number and name in the spaces at the top of this page.
Write in dark blue or black pen.
You may use an HB pencil for any diagrams, graphs or rough working.
Do not use staples, paper clips, glue or correction fluid.
DO NOT WRITE IN ANY BARCODES.
At the end of the examination, fasten all your work securely together.
The number of marks is given in brackets [ ] at the end of each question or part question.
DC (ST/SW) 115877/3
© UCLES 2016 [Turn over
2
1 A user can lock a safety deposit box by inputting a 4-digit code. The user can unlock the box with
the same 4-digit code.
There is a keypad on the door of the safety deposit box. The following diagram shows the keys on
the keypad.
1 2 3
4 5 6
7 8 9
R 0 Enter
Initially, the safety deposit box door is open and the user has not set a code.
A) To set a new code the door must be open. The user chooses a 4-digit code and sets it by
pressing the numerical keys on the keypad, followed by the Enter key. Until the user clears
this code, it remains the same. (See point E below)
B) The user can only close the door if the user has set a code.
C) To lock the door, the user closes the door, enters the set code and presses the Enter key.
D) To unlock the door, the user enters the set code. The door then opens automatically.
E) The user clears the code by opening the door and pressing the R key, followed by the Enter
key. The user can then set a new code. (See point A above)
The following state transition table shows the transition from one state to another of the safety
deposit box:
.......................................................
start
............................
Door open
no code set
............................
......................................
...............................................
...............................................
Door closed
............................
............................
...............................................
...............................................
[7]
(b) A company wants to simulate the use of a safety deposit box. It will do this with object-oriented
programming (OOP).
The following diagram shows the design for the class SafetyDepositBox. This includes the
properties and methods.
SafetyDepositBox
Code : STRING // 4 digits
State : STRING // "Open-NoCode", "Open-CodeSet", "Closed"
// or "Locked"
Create() // method to create and initialise an object
// if using Python use __init__
Reset() // clears Code
SetState() // set state to parameter value
// and output new state
SetNewCode() // sets Code to parameter value
// output message and new code
StateChange() // reads keypad and takes appropriate action
(i) Create()
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [3]
(ii) Reset()
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [2]
(iii) SetState()
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [2]
(iv) SetNewCode()
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [2]
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [4]
(vi) Convert the flowchart to program code for the method StateChange(). Use the
properties and methods in the original class definition and the Valid() function from
part (v).
METHOD StateChange
INPUT Chars
No No
CALL SetState("Open-NoCode")
No No
Is State = Yes
CALL SetState("Locked")
"Closed"?
No
No
No No
CALL SetState("Open-CodeSet")
OUTPUT "Error – OUTPUT "Error –
code format does not match
incorrect" set code"
ENDMETHOD
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.....................................................................................................................................[12]
(vii) The company needs to write a program to simulate a safety deposit box. The program
will create an object with identifier ThisSafe, which is an instance of the class
SafetyDepositBox.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [4]
The programmer has modified the class design for SafetyDepositBox as follows:
SafetyDepositBox
PRIVATE
Code : STRING
State : STRING
PUBLIC
Create()
StateChange()
PRIVATE
Reset()
SetState()
SetNewCode()
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [2]
(ii) Describe the effects of declaring two methods of the class as public and the other three
as private.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [2]
(a) (i) Name the programming environment you have used when typing in program code.
...........................................................................................................................................
...........................................................................................................................................
List three features of the editor that helped you to write program code.
1 ........................................................................................................................................
...........................................................................................................................................
2 ........................................................................................................................................
...........................................................................................................................................
3 ........................................................................................................................................
...................................................................................................................................... [3]
(ii) Explain when and how your programming environment reports a syntax error.
When .................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
How ...................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [2]
(iii) The table shows a module definition for BinarySearch in three programming languages.
A B C
A) Python
01 def BinarySearch(List, Low, High, SearchItem):
02 Index = -1
03 while (Index == -1) AND (Low <= High):
04 Middle = (High + Low) // 2
05 if List[Middle] == SearchItem:
06 Index = Middle
07 elif List[Middle] < SearchItem:
08 Low = Middle + 1
09 else:
10 High = Middle - 1
11 return(Middle)
B) Pascal/Delphi
01 FUNCTION BinarySearch(VAR List : ARRAY OF INTEGER; Low, High,
SearchItem : INTEGER) : INTEGER;
02 VAR Index, Middle : INTEGER;
03 BEGIN
04 Index := -1;
05 WHILE (Index = -1) & (Low <= High) DO
06 BEGIN
07 Middle := (High + Low) DIV 2;
08 IF List[Middle] = SearchItem
09 THEN Index := Middle
10 ELSE IF List[Middle] < SearchItem
11 THEN Low := Middle + 1
12 ELSE High := Middle - 1;
13 END;
14 Result := Middle;
15 END;
C) Visual Basic
01 Function BinarySearch(ByRef List() As Integer, ByVal Low As Integer,
ByVal High As Integer, ByVal SearchItem As Integer) As Integer
02 Dim Index, Middle As Integer
03 Index = -1
04 Do While (Index = -1) & (Low <= High)
05 Middle = (High + Low) \ 2
06 If List(Middle) = SearchItem Then
07 Index = Middle
08 ElseIf List(Middle) < SearchItem Then
09 Low = Middle + 1
10 Else
11 High = Middle - 1
12 End If
13 Loop
14 BinarySearch = Middle
15 End Function
.......................................................................................................................................[2]
(b) (i) State whether programs written in your programming language are compiled or
interpreted.
...........................................................................................................................................
...................................................................................................................................... [1]
(ii) A programmer corrects the syntax error and tests the function. It does not perform as
expected when the search item is not in the list.
...........................................................................................................................................
.......................................................................................................................................[2]
(iii) State the programming environment you have used when debugging program code.
...........................................................................................................................................
...........................................................................................................................................
Name two debugging features and describe how they are used.
1 ........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
2 ........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [4]
3 The following table shows part of the instruction set for a processor which has one general purpose
register, the Accumulator (ACC), and an index register (IX).
Instruction
Op Explanation
Operand
code
LDM #n Immediate addressing. Load the number n to ACC.
LDD <address> Direct addressing. Load the contents of the given address to ACC.
Indexed addressing. Form the address from <address> + the contents
LDX <address> of the index register. Copy the contents of this calculated address to
ACC.
LDR #n Immediate addressing. Load the number n into IX.
STO <address> Store the contents of ACC at the given address.
INC <register> Add 1 to the contents of the register (ACC or IX).
DEC <register> Subtract 1 from the contents of the register (ACC or IX).
CMP <address> Compare the contents of ACC with the contents of <address>.
CMP #n Compare the contents of ACC with number n.
Following a compare instruction, jump to <address> if the compare
JPE <address>
was True.
Following a compare instruction, jump to <address> if the compare
JPN <address>
was False.
Output to the screen the character whose ASCII value is stored in
OUT
ACC.
END Return control to the operating system.
A programmer is writing a program that outputs a string, first in its original order and then in
reverse order.
The program will use locations starting at address NAME to store the characters in the string. The
location with address MAX stores the number of characters that make up the string.
The programmer has started to write the program in the table opposite. The Comment column
contains descriptions for the missing program instructions.
Complete the program using op codes from the given instruction set.
Op
Label Operand Comment
code
START: // initialise index register to zero
// is COUNT = MAX ?
// store in COUNT
// is COUNT = MAX ?
// end of program
COUNT:
MAX: 4
[15]
© UCLES 2016 9608/41/O/N/16 [Turn over
16
Who ..........................................................................................................................................
...................................................................................................................................................
When ........................................................................................................................................
...................................................................................................................................................
Purpose ....................................................................................................................................
...............................................................................................................................................[3]
Who ..........................................................................................................................................
...................................................................................................................................................
When ........................................................................................................................................
...................................................................................................................................................
Purpose ....................................................................................................................................
...............................................................................................................................................[3]
Permission to reproduce items where third-party owned material protected by copyright is included has been sought and cleared where possible. Every reasonable
effort has been made by the publisher (UCLES) to trace copyright holders, but if any items requiring clearance have unwittingly been included, the publisher will
be pleased to make amends at the earliest possible opportunity.
To avoid the issue of disclosure of answer-related information to candidates, all copyright acknowledgements are reproduced online in the Cambridge International
Examinations Copyright Acknowledgements Booklet. This is produced for each series of examinations and is freely available to download at www.cie.org.uk after
the live examination series.
Cambridge International Examinations is part of the Cambridge Assessment Group. Cambridge Assessment is the brand name of University of Cambridge Local
Examinations Syndicate (UCLES), which is itself a department of the University of Cambridge.
1 (a) 1 mark for both Set code entered correct. 1 mark for each label. [7]
PYTHON:
def __init__(self):
self.__code = ""
self.__state = "Open-NoCode"
PASCAL/DELPHI:
constructor SafetyDepositBox.Create();
begin
Code := '';
State := 'Open-NoCode';
end;
© UCLES 2016
Page 3 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2016 9608 41
VB:
Public Sub New()
Code = ""
State = "Open-NoCode"
End Sub
PYTHON:
def reset(self):
self.__code = ""
PASCAL/DELPHI:
procedure SafetyDepositBox.Reset();
begin
Code := '';
end;
VB:
Public Sub Reset()
Code = ""
End Sub
PYTHON:
def SetState(self,NewState):
self.__state = NewState
print(self.__state)
PASCAL/DELPHI:
Procedure SetState(NewState : String);
begin
State := NewState
WriteLn(State)
end;
© UCLES 2016
Page 4 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2016 9608 41
VB: VB:
Public Sub SetState(ByVal Private _State As String
NewState As String) Public Property State() As
State = NewState String
Console.WriteLine(State) Get
End Sub Return _State
End Get
Set(value As String)
_State = value
End Set
End Property
Public Sub SetState()
Console.WriteLine(Me.State)
End Sub
PYTHON:
def SetNewCode(self, NewCode):
self.__code = NewCode
print("New code set: ", self.__code)
PASCAL/DELPHI:
procedure SetNewCode(NewCode : String);
begin
Code := NewCode;
WriteLn('New code set: ', Code)
end;
VB:
Public Sub SetNewCode(NewCode)
Code = NewCode
Console.WriteLine("New code set: " & Code)
End Sub
© UCLES 2016
Page 5 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2016 9608 41
PYTHON:
def __valid(self, s):
digits = ['0','1','2','3','4','5','6','7','8','9']
isValid = False
if (len(s) == 4):
if (s[0] in digits) & (s[1] in digits) & (s[2] in digits) &
(s[3] in digits):
isValid = True
return(isValid)
PASCAL/DELPHI:
function Valid(s : string) : Boolean;
var isValid : Boolean; i : integer;
begin
isValid := False
if Length(s) = 4
then
begin
isValid := True;
For i := 1 to 4 do
if (s[i] < '0') OR (s[i] > '9')
then
isValid := False;
end;
end;
© UCLES 2016
Page 6 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2016 9608 41
PYTHON:
def StateChange(self):
Chars = input("Enter code: ")
if Chars == "R":
if self.__state == "Open-CodeSet":
self.reset()
self.SetState("Open-NoCode")
elif Chars == self.__code:
if self.__state == "Locked":
self.SetState("Open-CodeSet")
elif self.__state == "Closed":
self.SetState("Locked")
elif (Chars == "")
& (self.__state == "Open-CodeSet"):
self.SetState("Closed")
elif self.__valid(Chars):
if self.__state == "Open-NoCode":
self.SetNewCode(Chars)
self.SetState("Open-CodeSet")
else:
print("Error - does not match set code")
else:
print("Error - Code format incorrect")
© UCLES 2016
Page 7 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2016 9608 41
PASCAL/DELPHI:
Procedure StateChange();
var Chars : String;
begin
ReadLn(Chars);
If Chars = 'R' Then
If State = 'Open-CodeSet' Then
begin
Reset();
SetState('Open-NoCode');
end
Else
If Chars = Code Then
If state = 'Locked' Then
SetState('Open-CodeSet')
Else
If state = 'Closed' Then
SetState('Locked')
Else
If (Chars = '') AND (State = 'Open-CodeSet') Then
SetState('Closed')
Else
If Valid(Chars) Then
begin
If State == 'Open-NoCode' Then
begin
SetNewCode(Chars);
SetState('Open-CodeSet');
end
else
WriteLn('Error - does not match set code')
end
Else
WriteLn('Error - Code format incorrect');
end;
© UCLES 2016
Page 8 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2016 9608 41
VB:
Public Sub StateChange()
Dim Chars As String
Chars = Console.ReadLine()
If Chars = "R" Then
If State = "Open-CodeSet" Then
Reset()
SetState("Open-NoCode")
End If
ElseIf Chars = Code Then
If state = "Locked" Then
SetState("Open-CodeSet")
ElseIf state = "Closed" Then
SetState("Locked")
End If
ElseIf (Chars = "") AND (State = "Open-CodeSet") Then
SetState("Closed")
ElseIf Valid(Chars) Then
If State == "Open-NoCode" Then
SetNewCode(Chars)
SetState("Open-CodeSet")
Else
Console.WriteLine("Error - does not match set code")
End If
Else
Console.WriteLine("Error - Code format incorrect")
End If
End Sub
PYTHON:
def main():
ThisSafe = SafetyDepositBox()
while True:
ThisSafe.StateChange()
PASCAL/DELPHI:
var ThisSafe : SafetyDepositBox;
ThisSafe := SafetyDepositBox.Create;
while True do
ThisSafe.StateChange;
© UCLES 2016
Page 9 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2016 9608 41
VB:
Sub Main()
Dim ThisSafe As New SafetyDepositBox()
Do
ThisSafe.StateChange()
Loop
End Sub
(ii) Read and mark the answer as one paragraph. Mark a 'how' and a 'when' anywhere in
the answer. [2]
1 mark for when, 1 mark for how.
e.g.
When:
• the error has been typed
• when the program is being run/compiled/interpreted
How:
• highlights/underlines
displays error message/pop-up
(iii)
A B C
© UCLES 2016
Page 10 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2016 9608 41
(ii)
Logic error Logic error Logic error [1]
• breakpoint
• a point where the program can be halted to see if the program works at this point
© UCLES 2016
Page 11 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2016 9608 41
3
START: LDR #0 // initialise index register to zero [1]
LDM #0 // initialise COUNT to zero
[1]
STO COUNT
// load character from indexed address
LOOP1: LDX NAME
NAME [1]
© UCLES 2016
Page 12 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2016 9608 41
4
Acceptance testing Integration testing
Who The end user // user of the The programmer / in-house testers [1] +
software [1]
When When the software is When the separate modules have been [1] +
finished/ when it is installed written and tested [1]
Purpose To ensure the software is To ensure the modules work together as [1] +
what the customer ordered expected [1]
// to check that the software
meets the user requirements
© UCLES 2016
Cambridge International Examinations
Cambridge International Advanced Subsidiary and Advanced Level
Candidates should use this material in preparation for the examination. Candidates should attempt the
practical programming tasks using their chosen high-level, procedural programming language.
DC (NF/SW) 144918/4 R
© UCLES 2017 [Turn over
2
Teachers and candidates should read this material prior to the June 2017 examination for 9608 Paper 4.
Reminders
• there will be questions on the examination paper which do not relate to this pre-release material
• you must choose a high-level programming language from this list:
Note: A mark of zero will be awarded if a programming language other than those listed is used.
The practical skills for Paper 4 build on the practical skills covered in Paper 2. We therefore recommend
that candidates choose the same high-level programming language for this paper as they did for
Paper 2. This will give candidates the opportunity for extensive practice and allow them to acquire
sufficient expertise.
• structured English
• pseudocode
• program code
Candidates will also benefit from using pre-release materials from previous examinations. These are
available on the teacher support site.
Declaration of variables
The syllabus document shows the syntax expected for a declaration statement in pseudocode.
If Python is the chosen language, each variable’s identifier (name) and its intended data type must be
documented using a comment statement.
TASK 1
Students at a college are given several tests during their course. A teacher wants to write
object-oriented software to process data about the tests.
For each test, the following are to be stored:
TASK 1.1
The relationship between Test and Question is shown in the following containment (aggregation)
class diagram.
Test Question
– TestID : String – QuestionID : String
– Questions [1 : 10] : Question – QuestionText : String
– NumberOfQuestions : Integer – Answer : String
1 1..*
– MaxMarks : Integer – Marks : Integer
– Level : Char – Topic : String
– DateSet : Date
+ SetQuestion()
+ DesignTest() + GetQuestion() : String
+ PrintTest() + GetMarks() : Integer
+ PrintAnswers() + GetTopic() : String
+ GetAnswer() : String
TASK 1.2
TASK 2
The table shows part of the instruction set for a processor which has one general purpose register, the
Accumulator (ACC), and an Index Register (IX).
Note: these instructions are referred to in the syllabus sections 1.4.3 and 3.6.2.
Instruction
Op Explanation
Operand
code
LDM #n Immediate addressing. Load the number n to ACC.
Direct addressing. Load the contents of the location at the given address to
LDD <address>
ACC.
Indirect addressing. The address to be used is at the given address. Load the
LDI <address>
contents of this second address to ACC.
Indexed addressing. Form the address from <address> + the contents of the
LDX <address>
index register. Copy the contents of this calculated address to ACC.
LDR #n Immediate addressing. Load the number n into IX.
STO <address> Store the contents of ACC at the given address.
ADD <address> Add the contents of the given address to the ACC.
INC <register> Add 1 to the contents of the register (ACC or IX).
DEC <register> Subtract 1 from the contents of the register (ACC or IX).
JMP <address> Jump to the given address.
CMP <address> Compare the contents of ACC with the contents of <address>.
CMP #n Compare the contents of ACC with number n.
JPE <address> Following a compare instruction, jump to <address> if the compare was TRUE.
JPN <address> Following a compare instruction, jump to <address> if the compare was FALSE.
AND #n Bitwise AND operation of the contents of ACC with the operand.
AND <address> Bitwise AND operation of the contents of ACC with the contents of <address>.
XOR #n Bitwise XOR operation of the contents of ACC with the operand.
XOR <address> Bitwise XOR operation of the contents of ACC with the contents of <address>.
OR #n Bitwise OR operation of the contents of ACC with the operand.
OR <address> Bitwise OR operation of the contents of ACC with the contents of <address>.
IN Key in a character and store its ASCII value in ACC.
OUT Output to the screen the character whose ASCII value is stored in ACC.
END Return control to the operating system.
Notes:
Tasks 2.1 to 2.7 all use one of the following two formats for symbolic addressing.
Format Example
<label>: <op code> <operand> START: LDM #0
<label>: <data> NUM1: B01001010
Tasks 2.1 to 2.5 show high-level language constructs written in pseudocode. Each task consists of
writing the assembly language equivalent of the given high-level language construct.
Write assembly language program code using the given instruction set.
TASK 2.1
X A + B
END
Instruction
Label Op Comment
Operand
code
X:
A: 5
B: 3
TASK 2.2
IF X = A
THEN
OUTPUT CHR(X) // statements for THEN part
ELSE
A A + 1 // statements for ELSE part
ENDIF
END
Instruction
Label Op Comment
Operand
code
A: 65
X: 67
Note: the built-in function CHR(X) returns the character that is represented by the ASCII code held
in X.
TASK 2.3
REPEAT
OUTPUT CHR(X)
X X - 1
UNTIL X = A
END
Instruction
Label Op Comment
Operand
code
X: 90
A: 65
TASK 2.4
FOR COUNT 1 TO 4
OUTPUT CHARS[COUNT]
ENDFOR
END
Instruction
Label Op Comment
Operand
code
// set ACC to 1
// set IX to 0
// increment IX
// jump to LOOP
COUNT:
CHARS: 72 // 'H'
69 // 'E'
76 // 'L'
80 // 'P'
TASK 2.5
WHILE X <> B
OUTPUT CHARS[B]
B B + 1
ENDWHILE
END
Instruction
Label Op Comment
Operand
code
LOOP: // load contents of X into ACC
// is contents of ACC = contents of B ?
// if equal (TRUE), jump to ENDWHILE
// instructions to be repeated start here
// set IX to B starts here
// set ACC to 1
// store content of ACC in FORCOUNT
// FORCOUNT = B + 1 ? starts here
// decrement ACC to FORCOUNT - 1
// FORCOUNT – 1 = B ?
// if equal (TRUE), jump to ENDFOR
// increment IX
TASK 2.6
Instruction
Address Op Comment
Operand
code
// use indirect addressing to load contents of
LOOP:
address found at address 100
// increment ACC
100 102
101
102 77 // 'M'
103 65 // 'A'
104 84 // 'T'
105 72 // 'H'
106 83 // 'S'
107
TASK 2.7
Programmers use bitwise operations (AND, OR, XOR) to set or examine specific bits.
Example:
Instruction
Label Op Comment
Operand
code
X: B10101111
MASK: B00000001
Write simple programs using the different bitwise operations (AND, OR, XOR) and different MASK content.
Permission to reproduce items where third-party owned material protected by copyright is included has been sought and cleared where possible. Every
reasonable effort has been made by the publisher (UCLES) to trace copyright holders, but if any items requiring clearance have unwittingly been included, the
publisher will be pleased to make amends at the earliest possible opportunity.
To avoid the issue of disclosure of answer-related information to candidates, all copyright acknowledgements are reproduced online in the Cambridge International
Examinations Copyright Acknowledgements Booklet. This is produced for each series of examinations and is freely available to download at www.cie.org.uk after
the live examination series.
Cambridge International Examinations is part of the Cambridge Assessment Group. Cambridge Assessment is the brand name of University of Cambridge Local
Examinations Syndicate (UCLES), which is itself a department of the University of Cambridge.
Write your Centre number, candidate number and name in the spaces at the top of this page.
Write in dark blue or black pen.
You may use an HB pencil for any diagrams, graphs or rough working.
Do not use staples, paper clips, glue or correction fluid.
DO NOT WRITE IN ANY BARCODES.
At the end of the examination, fasten all your work securely together.
The number of marks is given in brackets [ ] at the end of each question or part question.
DC (RW/SW) 129953/3
© UCLES 2017 [Turn over
2
1 The following table shows part of the instruction set for a processor which has one general purpose
register, the Accumulator (ACC), and an Index Register (IX).
Instruction
Op Explanation
Operand
code
LDM #n Immediate addressing. Load the number n to ACC.
Direct addressing. Load the contents of the location at the given address
LDD <address>
to ACC.
Indirect addressing. The address to be used is at the given address.
LDI <address>
Load the contents of this second address to ACC.
Indexed addressing. Form the address from <address> + the contents of
LDX <address>
the index register. Copy the contents of this calculated address to ACC.
STO <address> Store the contents of ACC at the given address.
INC <register> Add 1 to the contents of the register (ACC or IX).
DEC <register> Subtract 1 from the contents of the register (ACC or IX).
CMP <address> Compare the contents of ACC with the contents of <address>.
JMP <address> Jump to given address.
Following a compare instruction, jump to <address> if the compare was
JPE <address>
True.
Following a compare instruction, jump to <address> if the compare was
JPN <address>
False.
Bitwise AND operation of the contents of ACC with the contents of
AND <address>
<address>.
Bitwise XOR operation of the contents of ACC with the contents of
XOR <address>
<address>.
Bitwise OR operation of the contents of ACC with the contents of
OR <address>
<address>.
IN Key in a character and store its ASCII value in ACC.
OUT Output to the screen the character whose ASCII value is stored in ACC.
END Return control to the operating system.
ABCDEFG
The programmer has started to write the program in the table on the following page. The
Comment column contains descriptions for the missing instructions, labels and data.
Complete the following program. Use op codes from the given instruction set.
// store in CHAR
// OUTPUT ACC
// increment ACC
// jump to LOOP
ENDFOR: END
CHAR:
[8]
• tests whether an 8-bit two’s complement integer stored at address NUMBER is positive or
negative
• outputs 'P' for a positive integer and 'N' for a negative integer.
Complete the following program. Use op codes from the given instruction set.
Show the required value of MASK in binary.
// compare with 0
JMP ENDIF
ENDIF:
END
[7]
© UCLES 2017 9608/41/M/J/17 [Turn over
4
Each record consists of a unique customer ID, the record key, and other customer data.
TYPE CustomerRecord
CustomerID : INTEGER
Data : STRING
ENDTYPE
PROCEDURE CreateHashTable()
............................................................................................................................................
............................................................................................................................................
............................................................................................................................................
............................................................................................................................................
ENDPROCEDURE [4]
(b) A hashing function Hash exists, which takes as a parameter the customer ID and returns an
integer in the range 0 to 199 inclusive.
The procedure makes use of the function Hash. Collisions will be managed using open
hashing. This means a collision is resolved by storing the record in the next available
location. The procedure will generate an error message if the hash table is full.
TableFull FALSE
Index ..................................................................................................................
WHILE ........................................................................................................................
Pointer .......................................................................................................
IF ........................................................................................................................
THEN
.................................................................................................................
ENDIF
IF ........................................................................................................................
THEN
TableFull TRUE
ENDIF
ENDWHILE
IF ..............................................................................................................................
THEN
........................................................................................................................
ELSE
........................................................................................................................
ENDIF
ENDPROCEDURE [9]
(ii) The function SearchHashTable will search for a record in the hash table. The function
takes as a parameter the customer ID to be searched for. The function will return the
position in the hash table where the record has been saved. If the hash table does not
contain the record, the function will return the value −1.
You can assume that there is at least one empty record in the hash table.
Index ..................................................................................................................
WHILE ( ....................................................................................................................)
AND (..................................................................................................................)
..............................................................................................................................
// wrap if necessary
IF ........................................................................................................................
THEN
.................................................................................................................
ENDIF
ENDWHILE
IF ..............................................................................................................................
THEN
........................................................................................................................
ELSE
........................................................................................................................
ENDIF
ENDFUNCTION [9]
...........................................................................................................................................
.......................................................................................................................................[1]
© UCLES 2017 9608/41/M/J/17
7
3 NameList is a 1D array that stores a sorted list of names. A programmer declares the array in
pseudocode as follows:
The programmer wants to search the list using a binary search algorithm.
The programmer decides to write the search algorithm as a recursive function. The function, Find,
takes three parameters:
The function will return the position of the name in the list, or −1 if the name is not found.
// base case
IF .............................................................................................................................................
THEN
RETURN −1
ELSE
Middle ..................................................................................................................
IF ................................................................................................................................
THEN
RETURN ...........................................................................................................
THEN
.............................................................................................................
ELSE
.............................................................................................................
ENDIF
ENDIF
ENDIF
ENDFUNCTION [7]
© UCLES 2017 9608/41/M/J/17 [Turn over
8
4 An ordered linked list Abstract Data Type (ADT) has these associated operations:
• create list
• add item to list
• output list to console
(i) State the term used to describe the relationship between these classes.
.......................................................................................................................................[1]
(ii) Draw the appropriate diagram to represent this relationship. Do not list the attributes and
methods of the classes.
[2]
• attributes
Data : STRING
Pointer : INTEGER
• methods
CreateNode(Data, Pointer)
SetData(Data)
SetPointer(Pointer)
GetData() RETURNS STRING
GetPointer() RETURNS INTEGER
The constructor method sets the attributes to the initial values that are passed as parameters.
Program code
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...............................................................................................................................................[5]
© UCLES 2017 9608/41/M/J/17 [Turn over
10
The following diagram shows an example of a linked list object. This example list consists of
three nodes, linked in alphabetical order of the data strings. The unused nodes are linked to
form a free list.
HeadPointer
Berlin London Paris Ø
node node node
FreeListPointer
Ø
node node node node
...........................................................................................................................................
.......................................................................................................................................[1]
© UCLES 2017 9608/41/M/J/17
11
(ii) Give an appropriate value to represent the null pointer for this design. Justify your
answer.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[2]
(iii) Write program code for the LinkedList class declaration and the constructor.
Program code
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[7]
© UCLES 2017 9608/41/M/J/17 [Turn over
12
(iv) Write program code to instantiate a linked list object with the contacts identifier.
Program code
...........................................................................................................................................
.......................................................................................................................................[1]
(v) The OutputListToConsole method is to output all the data stored in the linked list.
HeadPointer points to the first list node.
Program code
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[5]
THEN
ELSE
// FindInsertionPoint provides
THEN
ELSE
The FindInsertionPoint method receives the new data item as the parameter
NewString. It returns two parameters:
• PreviousPointer, whose value is:
either the pointer to the node before the insertion point
or the null pointer, if the new node is to be inserted at the beginning of the list.
• NextPointer, whose value is the pointer to the node after the insertion point.
Program code
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[6]
© UCLES 2017 9608/41/M/J/17
Cambridge International Examinations
Cambridge International Advanced Subsidiary and Advanced Level
Published
This mark scheme is published as an aid to teachers and candidates, to indicate the requirements of the
examination. It shows the basis on which Examiners were instructed to award marks. It does not indicate the
details of the discussions that took place at an Examiners’ meeting before marking began, which would have
considered the acceptability of alternative answers.
Mark schemes should be read in conjunction with the question paper and the Principal Examiner Report for
Teachers.
Cambridge will not enter into discussions about these mark schemes.
Cambridge is publishing the mark schemes for the May/June 2017 series for most Cambridge IGCSE®,
Cambridge International A and AS Level and Cambridge Pre-U components, and some Cambridge O Level
components.
1(a) Op 8
Label Operand Comment
code
START: IN // INPUT character
STO CHAR // store in CHAR 1
// Initialise ACC
LDM #65 (ASCII value for 1
'A' is 65)
LOOP: OUT // OUTPUT ACC 1+1
// compare ACC with
CMP CHAR 1
CHAR
// if equal jump to
JPE ENDFOR 1
end of FOR loop
INC ACC // increment ACC 1
JMP LOOP // jump to LOOP 1
ENDFOR: END
CHAR:
FOR x ← 0 TO 199 1
Customer[x].CustomerID ← 0 1+1
ENDFOR
IF Customer[Index].CustomerID = SearchID 1
THEN
RETURN Index 1
ELSE
RETURN -1 1
ENDIF
ENDFUNCTION
4(a)(i) containment/aggregation 1
4(a)(ii) Max 2
1 mark for the two classes (in boxes) and connection with correct end point
1 mark for 0 ..* 0
Python Example
class Node: 1
def __init__(self, D, P): 1+1
self.__Data = D 1
self.__Pointer = P 1
return
Example Pascal
type
Node = class 1
private 1
Data : String;
Pointer : Integer;
public
constructor Create(D : string; P : integer);
procedure SetPointer(P : Integer);
procedure SetData(D : String);
function GetData() : String; ignore
function GetPointer() : Integer;
end;
constructor Node.Create(D : string; P : integer); 1+1
begin
Data := D;
Pointer := P; 1
end;
Example VB.NET
Class Node 1
Private Data As String
Private Pointer As Integer 1
Public Sub New(ByVal D As String, ByVal P As Integer) 1+1
Data = D
Pointer = P 1
End Sub
End Class
Python Example
class LinkedList: 1
def __init__(self): 1
self.__HeadPointer = - 1 1
self.__FreeListPointer = 0 1
self.__NodeArray = []
for i in range(8): 1
ThisNode = Node("", (i + 1)) 1
self.__NodeArray.append(ThisNode)
self.__NodeArray[7].SetPointer(- 1) 1
Example Pascal
type
LinkedList = class 1
private
HeadPointer : Integer;
FreeList : Integer;
NodeArray : Array[0..7] of Node;
public
constructor Create();
procedure FindInsertionPoint(NewData : string; var
PreviousPointer, NextPointer : integer);
procedure AddToList(NewData : string);
procedure OutputListToConsole();
end;
constructor LinkedList.Create(); 1
var i : integer;
begin
HeadPointer := -1; 1
FreeList := 0; 1
for i := 0 To 7 do 1
NodeArray[i] := Node.Create('', (i + 1)); 1
NodeArray[7].SetPointer(-1); 1
end;
Example VB.NET
Class LinkedList 1
Private HeadPointer As Integer
Private FreeList As Integer
Private NodeArray(7) As Node
Python Example
contacts = LinkedList()
Pascal Example
var contacts : LinkedList;
contacts := LinkedList.Create;
VB.NET Example
Dim contacts As New LinkedList
Python Example
def OutputListToConsole(self) :
Pointer = self.__HeadPointer 1
while Pointer != -1 : 1
print(self.__NodeArray[Pointer].GetData()) 1+1
Pointer = self.__NodeArray[Pointer].GetPointer() 1
print()
return
Pascal Example
procedure LinkedList.OutputListToConsole();
var Pointer : integer;
begin
Pointer := HeadPointer; 1
while Pointer <> -1 do 1
begin
WriteLn(NodeArray[Pointer].GetData); 1+1
Pointer := NodeArray[Pointer].GetPointer; 1
end;
end;
VB.NET Example
Python Example
def AddToList(self, NewData):
NewNodePointer = self.__FreeListPointer
self.__NodeArray[NewNodePointer].SetData(NewData)
self.__FreeListPointer =
self.__NodeArray[self.__FreeListPointer].GetPointer()
if self.__HeadPointer == -1:
self.__HeadPointer = NewNodePointer
self.__NodeArray[NewNodePointer ].SetPointer(-1)
else:
PreviousPointer, NextPointer = self.FindInsertionPoint(NewData)
if PreviousPointer == -1 :
self.__NodeArray[NewNodePointer ].SetPointer
(self.__HeadPointer)
self.__HeadPointer = NewNodePointer
else:
self.__NodeArray[NewNodePointer ].SetPointer(NextPointer)
self.__NodeArray[PreviousPointer].SetPointer(NewNodePointer)
Pascal Example
procedure LinkedList.AddToList(NewData : string);
var NewNodePointer , PreviousPointer,
NextPointer : integer;
begin
// make a copy of free list pointer
NewNodePointer := FreeListPointer;
// store new data item in free node
NodeArray[NewNodePointer].SetData(NewData);
// adjust free pointer
FreeListPointer :=
NodeArray[FreeListPointer].GetPointer;
// if list is currently empty
if HeadPointer = -1
then
// make the node the first node
begin
HeadPointer := NewNodePointer;
// set pointer to Null pointer
NodeArray[NewNodePointer].SetPointer(-1);
end
else
// find insertion point
begin
FindInsertionPoint(NewData, PreviousPointer,
NextPointer);
// if previous pointer is Null pointer
if PreviousPointer = -1
then
// link node to front of list
begin
NodeArray[NewNodePointer]
.SetPointer(HeadPointer);
HeadPointer := NewNodePointer ;
end
else
// link new node between
Previous node and next node
begin
NodeArray[NewNodePointer ]
.SetPointer(NextPointer);
NodeArray[PreviousPointer]
.SetPointer(NewNodePointer);
end;
end;
end;
VB.NET Example
Public Sub AddToList(ByVal NewData As String)
Dim NewNodePointer, PreviousPointer, NextPointer As Integer
' make copy of free list pointer
NewNodePointer= FreeListPointer
' store new data item in free node
NodeArray(NewNodePointer).SetData(NewData)
' adjust free pointer
FreeListPointer = NodeArray(FreeListPointer).GetPointer
' if list iscurrently empty
If HeadPointer = -1 Then
' make the node the first node
HeadPointer = NewNodePointer
' set pointer to Null pointer
NodeArray(NewNodePointer).SetPointer(-1)
Else
' find insertion point
FindInsertionPoint(NewData, PreviousPointer,
NextPointer)
' if previous pointer is Null pointer
If PreviousPointer = -1 Then
' link to front of list
NodeArray(NewNodePointer).SetPointer(HeadPointer)
HeadPointer = NewNodePointer
Else
' link new node between Previous node and next node
NodeArray(NewNodePointer).SetPointer(NextPointer)
NodeArray(PreviousPointer).SetPointer(NewNodePointer)
End If
End If
End Sub
PROCEDURE AddToList(NewData)
// remember value of free list pointer
NewNodePointer ← FreeListPointer
// add new data item to free node pointed to by free list
NodeArray[NewNodePointer].Data ← NewData
// adjust free pointer to point to next free node
FreeListPointer ← NodeArray[FreeList].Pointer
// is list currently empty?
IF HeadPointer = NullPointer
THEN
// make the node the first node
HeadPointer ← NewnodePointer
// set pointer of new node to Null pointer
NodeArray[NewNodePointer].Pointer ← NullPointer
ELSE
// find insertion point
CALL FindInsertionPoint(NewData, PreviousPPointer, NextPointer)
// if previous pointer is Null pointer
IF PreviousPointer = NullPointer
THEN
// link new node to front of list
NodeArray[NewNodePointer].Pointer ← HeadPointer
HeadPointer ← NewNodePointer
ELSE
// link new node between previous node and next node
NodeArray[NewNodePointer].Pointer ← NextPOinter
NodeArray[PreviousPointer].Pointer ← NewNodePointer
END IF
ENDIF
END PROCEDURE
This material should be given to the relevant teachers and candidates as soon as it has been received
at the Centre.
Candidates should use this material in preparation for the examination. Candidates should attempt the
practical programming tasks using their chosen high-level, procedural programming language.
DC (NH) 129952/4
© UCLES 2017 [Turn over
2
Teachers and candidates should read this material prior to the November 2017 examination for 9608
Paper 4.
Reminders
The syllabus states:
• there will be questions on the examination paper which do not relate to this pre-release material
• you must choose a high-level programming language from this list:
Visual Basic (console mode)
Python
Pascal / Delphi (console mode)
Note: A mark of zero will be awarded if a programming language other than those listed is used.
The practical skills for Paper 4 build on the practical skills covered in Paper 2. We therefore recommend
that candidates choose the same high-level programming language for this paper as they did for
Paper 2. This will give candidates the opportunity for extensive practice and allow them to acquire
sufficient expertise.
Candidates will also benefit from using pre-release materials from previous examinations. These are
available on the teacher support site.
Declaration of variables
The syllabus document shows the syntax expected for a declaration statement in pseudocode.
If Python is the chosen language, each variable’s identifier (name) and its intended data type must be
documented using a comment statement.
TASK 1
Key focus: Declarative programming
Some clauses in a declarative language are shown.
01 male(james).
02 male(alex).
03 male(richard).
04 female(sophie).
05 female(alexandra).
06 female(jane).
07 parent(jane, james).
08 parent(jane, alex).
09 parent(richard, james).
10 parent(richard, alex).
Clause Explanation
01 James is male
04 Sophie is female
07 Jane is a parent of James
TASK 1.1
TASK 1.2
TASK 1.3
TASK 1.4
Write a query for a sibling of a person. Two people are siblings if they have the same mother and
father. A person cannot be their own sibling.
TASK 1.5
Add clauses so that the knowledge base includes parents of parents. We call these ‘grandparents’.
TASK 1.6
TASK 1.7
• parent(richard, james).
• parent(james, richard).
TASK 2
Key focus: Low-level programming
The following table shows part of the instruction set for a processor that has one general purpose
register, the Accumulator (ACC), and an Index Register (IX).
Instruction
Explanation
Op code Operand
LDM #n Immediate addressing. Load the number n to ACC.
Direct addressing. Load the contents of the location at the given
LDD <address>
address to ACC.
Indirect addressing. The address to be used is at the given
LDI <address>
address. Load the contents of this second address to ACC.
Indexed addressing. Form the address from <address> + the
LDX <address> contents of the index register. Copy the contents of this calculated
address to ACC.
LDR #n Immediate addressing. Load the number n to IX.
STO <address> Store the contents of ACC at the given address.
Indexed addressing. Form the address from <address> + the
STX <address> contents of the index register. Copy the contents from ACC to this
calculated address.
ADD <address> Add the contents of the given address to the ACC.
INC <register> Add 1 to the contents of the register (ACC or IX).
DEC <register> Subtract 1 from the contents of the register (ACC or IX).
JMP <address> Jump to the given address.
CMP <address> Compare the contents of ACC with the contents of <address>.
CMP #n Compare the contents of ACC with number n.
Following a compare instruction, jump to <address> if the compare
JPE <address>
was True.
Following a compare instruction, jump to <address> if the compare
JPN <address>
was False.
Bits in ACC are shifted n places to the left. Zeros are introduced on
LSL #n
the right hand end.
Bits in ACC are shifted n places to the right. Zeros are introduced
LSR #n
on the left hand end.
IN Key in a character and store its ASCII value in ACC.
Output to the screen the character whose ASCII value is stored in
OUT
ACC.
END Return control to the operating system.
Notes:
Tasks 2.1 to 2.4 all use one of the following two formats for symbolic addressing.
Format Example
<label>: <op code> <operand> START: LDA #0
<label>: <data> NUM1: B01001010
TASK 2.1
Write a program in assembly language using the op codes from the given instruction set to divide a
number by 2 using a logical right shift.
TASK 2.2
Write a program in assembly language using the op codes from the given instruction set to multiply a
number by 2 using a logical left shift.
TASK 2.3
Write a program in assembly language using the op codes from the given instruction set to add together
a series of numbers stored in an array using indexed addressing.
TASK 2.4
Write a program in assembly language using the op codes from the given instruction set to take three
single digit numbers as input, and output the largest.
TASK 3
Key focus: Project management
TASK 3.1
Investigate project management techniques and diagrams that may be used to aid this process.
TASK 3.2
Think of a series of activities involved in completing a complex task and list the activities involved.
TASK 3.3
Complete the following table to show the activities from TASK 3.2, and develop a PERT chart to
represent your actions.
Write your Centre number, candidate number and name in the spaces at the top of this page.
Write in dark blue or black pen.
You may use an HB pencil for any diagrams, graphs or rough working.
Do not use staples, paper clips, glue or correction fluid.
DO NOT WRITE IN ANY BARCODES.
At the end of the examination, fasten all your work securely together.
The number of marks is given in brackets [ ] at the end of each question or part question.
DC (NH/JG) 129977/4
© UCLES 2017 [Turn over
2
1 A greenhouse has a window that automatically opens and closes depending on the internal
temperature.
If the temperature rises above 20 °C, the window half opens. If the temperature rises above 30 °C,
the window fully opens. If the temperature drops below 25 °C, the window returns to being half
open. If the temperature drops below 15 °C, the window fully closes.
The window has three possible states: Closed, Half Open and Fully Open.
.................................
.................................
.........................
.........................
.........................
.........................
.................................
.................................
.................................
.................................
.................................
.................................
.........................
.........................
[7]
2 (a) (i) State how repetition is shown in a Jackson Structured Programming (JSP) structure
diagram.
...........................................................................................................................................
.......................................................................................................................................[1]
...........................................................................................................................................
.......................................................................................................................................[1]
Draw a JSP diagram for the calculator. The first element is provided.
Calculator
[5]
01 person(jane).
02 person(ahmed).
03 person(caroline).
04 person(stuart).
05 food(chocolate).
06 food(sushi).
07 food(pizza).
08 food(chilli).
09 likes(jane, pizza).
10 likes(ahmed, chocolate).
11 likes(ahmed, pizza).
12 likes(jane, chilli).
13 likes(stuart, sushi).
14 dislikes(stuart, chocolate).
15 dislikes(jane, sushi).
16 dislikes(caroline, pizza).
Clause Explanation
01 Jane is a person
05 Chocolate is a food
09 Jane likes pizza
14 Stuart dislikes (does not like) chocolate
(a) Mimi is a person who likes chocolate but does not like sushi or lettuce.
17 .............................................................................................................................................
18 .............................................................................................................................................
19 .............................................................................................................................................
20 .............................................................................................................................................
21 .............................................................................................................................................
[5]
likes(PersonName, pizza).
returns:
likes(ahmed, FoodItem).
FoodItem = ............................................................................................................................
...............................................................................................................................................[2]
might_like(.................................................. , ..................................................)
IF .............................................................................................................................................
...................................................................................................................................................
...............................................................................................................................................[6]
4 The following table shows part of the instruction set for a processor. The processor has one
general purpose register, the Accumulator (ACC), and an Index Register (IX).
Instruction
Explanation
Op code Operand
LDM #n Immediate addressing. Load the number n to ACC.
LDD <address> Direct addressing. Load the contents of the location at the given
address to ACC.
LDI <address> Indirect addressing. The address to be used is at the given
address. Load the contents of this second address to ACC.
LDX <address> Indexed addressing. Form the address from <address> + the
contents of the index register. Copy the contents of this
calculated address to ACC.
LDR #n Immediate addressing. Load the number n to IX.
STO <address> Store the contents of ACC at the given address.
STX <address> Indexed addressing. Form the address from <address> + the
contents of the index register. Copy the contents from ACC to
this calculated address.
ADD <address> Add the contents of the given address to the ACC.
INC <register> Add 1 to the contents of the register (ACC or IX).
DEC <register> Subtract 1 from the contents of the register (ACC or IX).
JMP <address> Jump to the given address.
CMP <address> Compare the contents of ACC with the contents of <address>.
CMP #n Compare the contents of ACC with number n.
JPE <address> Following a compare instruction, jump to <address> if the
compare was True.
JPN <address> Following a compare instruction, jump to <address> if the
compare was False.
LSL #n Bits in ACC are shifted n places to the left. Zeros are introduced
on the right hand end.
LSR #n Bits in ACC are shifted n places to the right. Zeros are introduced
on the left hand end.
IN Key in a character and store its ASCII value in ACC.
OUT Output to the screen the character whose ASCII value is stored
in ACC.
END Return control to the operating system.
(a) A program stores a letter. The user is allowed nine attempts to guess the stored letter. The
program outputs “?” and the user guesses a letter. If the user guesses the letter, the program
outputs “*”.
REPEAT
OUTPUT '?'
INPUT GUESS
IF GUESS = LETTERTOGUESS
THEN
OUTPUT '*'
BREAK
ELSE
ATTEMPTS ATTEMPTS + 1
ENDIF
UNTIL ATTEMPTS = 9
Write this program. Use the op codes from the instruction set provided.
// increment ATTEMPTS
// is ATTEMPTS = 9 ?
// if out of guesses, go to ENDP
// go back to beginning of loop
GUESSED: LDM #42 // load ASCII for '*'
// OUTPUT '*'
ENDP: END // end program
ATTEMPTS: 0
LETTERTOGUESS: 'a'
[11]
(b) Five numbers are stored, starting in the location labelled NUMBERS. A program is needed to
multiply each of the numbers by 4 and store them back in their original location.
Write this program. Use the op codes from the instruction set on the opposite page.
// increment COUNT
// is COUNT = 5 ?
// repeat for next number
ENDP: END
COUNT: 0
NUMBERS: 22
13
5
46
12
[10]
Instruction
Explanation
Op code Operand
LDM #n Immediate addressing. Load the number n to ACC.
LDD <address> Direct addressing. Load the contents of the location at the given
address to ACC.
LDI <address> Indirect addressing. The address to be used is at the given
address. Load the contents of this second address to ACC.
LDX <address> Indexed addressing. Form the address from <address> + the
contents of the index register. Copy the contents of this
calculated address to ACC.
LDR #n Immediate addressing. Load the number n to IX.
STO <address> Store the contents of ACC at the given address.
STX <address> Indexed addressing. Form the address from <address> + the
contents of the index register. Copy the contents from ACC to
this calculated address.
ADD <address> Add the contents of the given address to the ACC.
INC <register> Add 1 to the contents of the register (ACC or IX).
DEC <register> Subtract 1 from the contents of the register (ACC or IX).
JMP <address> Jump to the given address.
CMP <address> Compare the contents of ACC with the contents of <address>.
CMP #n Compare the contents of ACC with number n.
JPE <address> Following a compare instruction, jump to <address> if the
compare was True.
JPN <address> Following a compare instruction, jump to <address> if the
compare was False.
LSL #n Bits in ACC are shifted n places to the left. Zeros are introduced
on the right hand end.
LSR #n Bits in ACC are shifted n places to the right. Zeros are introduced
on the left hand end.
IN Key in a character and store its ASCII value in ACC.
OUT Output to the screen the character whose ASCII value is stored
in ACC.
END Return control to the operating system.
(a) (i) Name an appropriate project management tool that helps the manager to work out the
estimated length of time it takes for the project to complete.
...........................................................................................................................................
.......................................................................................................................................[1]
(ii) Explain how, during the planning stage of the project, the manager would use the tool
you named in part (a)(i).
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[3]
(b) (i) Different programmers have been writing independent modules. The modules now need
to be combined to create the final system.
...........................................................................................................................................
.......................................................................................................................................[1]
(ii) Name the final testing stage required before the system becomes operational.
...........................................................................................................................................
.......................................................................................................................................[1]
6 A programmer wants to create a computer simulation of animals searching for food in a desert.
The desert is represented by a 40 by 40 grid. Each position in the grid is represented by a pair of
coordinates. 'A' represents an animal and 'F' represents food. At the start of the simulation, the
grid contains 5 animals and 1 food source.
0 1 2 3 4 ... 37 38 39
0 A ..
1 F ..
2 .. A
3 A ..
... .. .. .. .. .. .. .. .. ..
38 A .. A
39 ..
A timer is used. In each time interval, each animal randomly moves 0 or 1 position in a random
direction. The program generates this movement by computing two random numbers, each of
which can be –1, 0 or 1. The program adds the first random number to the across number and the
second random number to the down number representing the animal’s position.
For example:
• if 0 and 1 are generated, the across value does not change, the down value increases by 1
• if –1 and 1 are generated, the across value decreases by 1, and the down value increases
by 1.
Each animal has an individual score. If the animal moves to a position in the grid with food ('F'):
• attributes
• Grid
• StepCounter
• AnimalList
• NumberOfAnimals
• methods
• Constructor
• IncrementStepCounter
• GenerateFood
• DisplayGrid
Each attribute consists of a value and a get and set method that allow access to the attributes.
© UCLES 2017 9608/41/O/N/17 [Turn over
12
The following table describes the attributes and methods for the Animal class.
(a) Write program code to declare the attributes and constructor for the Animal class.
You only need to write the set and get methods for the attribute Across.
Program code
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...............................................................................................................................................[6]
Program code
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...............................................................................................................................................[5]
Program code
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[4]
(ii) The Move method uses the GenerateChangeInCoordinate function to calculate the
new Across and Down values for an animal. If there is food in the new position in the
grid, the animal eats the food.
Program code
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[4]
(d) The programmer plans to add a graphic display to the program. The programmer will make
use of a program library.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...............................................................................................................................................[2]
Permission to reproduce items where third-party owned material protected by copyright is included has been sought and cleared where possible. Every
reasonable effort has been made by the publisher (UCLES) to trace copyright holders, but if any items requiring clearance have unwittingly been included, the
publisher will be pleased to make amends at the earliest possible opportunity.
To avoid the issue of disclosure of answer-related information to candidates, all copyright acknowledgements are reproduced online in the Cambridge International
Examinations Copyright Acknowledgements Booklet. This is produced for each series of examinations and is freely available to download at www.cie.org.uk after
the live examination series.
Cambridge International Examinations is part of the Cambridge Assessment Group. Cambridge Assessment is the brand name of University of Cambridge Local
Examinations Syndicate (UCLES), which is itself a department of the University of Cambridge.
Window
Window half
closed open
For example:
Calculator
Display
Input x y Input sign Calculaon
answer
answer =
x+y
answer =
x–y
answer =
x*y
answer =
x/y
For example:
might_like(B, A).
IN // input GUESS 1
STO ATTEMPTS 1
CMP #9 // is ATTEMPTS = 9 ? 1
ATTEMPTS: 0
LETTERTOGUESS: 'a'
5(b)(i) Integration 1
6(a) Example: VB
Class Animal
Private Across As Integer
Private Down As Integer
Private Score As Integer
Function GetAcross()
Return Across
End Function
Sub SetAcross(Value As Integer)
Across = Value
End Sub
Sub New()
Randomize()
Across = randomnumber.Next(0, 40)
Down = randomnumber.Next(0, 40)
Score = 0
End Sub
End Class
6(a) or
Class Animal
Private Across As Integer
Property _Across As Integer
Get
Return _Across
End Get
Set(Value As Integer)
Across = Value
End Set
End Property
Private Down As Integer
Private _Score As Integer
Sub New()
Randomize()
Across = randomnumber.Next(0, 40)
Down = randomnumber.Next(0, 40)
_Score = 0
End Sub
End Class
Example: Python
class Animal :
def __init__ (self) :
x = random.randint(0,39)
y = random.randint(0,39)
self.Across = x
self.Down = y
self.Score = 0
def SetAcross(A) :
self.Across = A
def GetAcross() :
return self.Across
constructor Animal.init();
SetAcross(random(40));
SetDown (random(40));
SetScore (0);
end;
Example Python
Example VB
Sub New()
For x = 0 To 39
For y = 0 To 39
grid(x, y) = ""
Next
Next
For z = 0 To 4
AnimalList(z) = New Animal
Next
Call GenerateFood()
End Sub
© UCLES 2017 Page 11 of 15
9608/41 Cambridge International AS/A Level – Mark Scheme October/November
PUBLISHED 2017
Question Answer Marks
constructor Desert.init();
for x := 0 to 39 do
begin
for y := 0 to 39 do
begin
grid(x,y) = "";
end
end
for x := 0 to 4 do
begin
AnimalList(x) = object (Animal);
end
GenerateFood();
end;
6(c)(i) Example VB
If coord = 0 Then
lowerbound = 0
ElseIf coord = 39 Then
upperbound = 0
End If
End Function
Example Python
def GenerateDirection(Coord) :
lowerBound = -1
upperBound = 1
if Coord == 0 :
lowerBound = 0
elif Coord == 39 :
upperBound = 0
return random.randint(lowerBound, upperBound)
Example python
def Move(self) :
self.Across += GenerateChangeInCoordinate(self.Across)
self.Down += GenerateChangeInCoordinate(self.Down)
if grid[self.Across][self.Down] == 'F' :
self.EatFood()
return
6(c)(ii) Example VB
Example Pascal
Candidates should use this material in preparation for the examination. Candidates should attempt the
practical programming tasks using their chosen high-level, procedural programming language.
DC (LK) 147488/1
© UCLES 2018 [Turn over
2
Teachers and candidates should read this material prior to the June 2018 examination for 9608 Paper 4.
Reminders
The syllabus states:
• there will be questions on the examination paper which do not relate to this pre-release material
• you must choose a high-level programming language from this list:
Visual Basic (console mode)
Python
Pascal / Delphi (console mode)
Note: A mark of zero will be awarded if a programming language other than those listed is used.
The practical skills for Paper 4 build on the practical skills covered in Paper 2. We therefore recommend
that candidates choose the same high-level programming language for this paper as they did for
Paper 2. This will give candidates the opportunity for extensive practice and allow them to acquire
sufficient expertise.
• structured English
• pseudocode
• program code
A program flowchart or the use of Jackson Structured Programming (JSP) should be considered as an
alternative to pseudocode for documenting a high-level algorithm design.
Candidates will also benefit from using pre-release materials from previous examinations. These are
available on the teacher support site.
Declaration of variables
The syllabus document shows the syntax expected for a declaration statement in pseudocode.
If Python is the chosen language, each variable’s identifier (name) and its intended data type must be
documented using a comment statement.
Staff salaries are read from a file. The role of each member of staff is determined by their salary:
The following JSP structure diagram shows the structure of a solution for this problem.
Salary
Classification
*
Identify Role
FALSE TRUE
FALSE TRUE
TASK 1.1
TASK 1.2
Find out the meaning of the different symbols inside the boxes and how these affect the structure of
the program.
TASK 1.3
Complete the following pseudocode algorithm for the JSP structure diagram on the previous page.
WHILE .....................................................................................................................................................
CALL ReadSalary()
IF ......................................................................................................................................................
THEN
IF .........................................................................................................................................
THEN
Role ← .................................................................................................................
ELSE
Role ← .................................................................................................................
ENDIF
ELSE
Role ← ..............................................................................................................................
ENDIF
ENDWHILE
TASK 1.4
A new role is introduced. Any member of staff earning more than 70 and less than 90 is now called a
Consultant.
TASK 1.5
TASK 1.6
The function will take salary as its parameter, and return the role title.
A toy shop needs a computer system to store information about its toys.
TASK 2.1
Use the following incomplete class diagram to specify the three classes. Make sure you include the
constructor, and get and set methods for each class.
Toy
Key focus:
Class diagrams
ComputerGame Vehicle
TASK 2.2
The ComputerGame and Vehicle classes inherit from the Toy class.
TASK 2.3
TASK 2.4
Write program code to create the ComputerGame and Vehicle classes. Make sure:
TASK 2.5
Add validation (where appropriate) to the constructor and set methods for all three classes. For
example, age range may be limited to between 0 and 18.
TASK 2.6
Create instances of ComputerGame and Vehicle with appropriate data, in the main program. Store
the objects in arrays. The data for one instance of Vehicle is given to get you started.
TASK 2.7
A procedure prompts the user to input the ID for a toy. The program finds that toy and outputs the
values of its properties in an appropriate format.
TASK 2.8
A procedure allows the user to input a number to be used as a discount rate. The price of all the toys
will be reduced by that number. For example, 10 would reduce the price of all toys by 10%.
TASK 2.9
TASK 2.10
The shop would like the program to sort the objects in the ComputerGame class in ascending order of
price, and output the values of their properties.
Write at least one algorithm to sort and output the arrays in ascending order of price.
A declarative language is used to create a set of facts and rules for characters in a computer game.
01 character(jim).
02 character(jenny).
03 character_type(jim, prince).
04 character_type(jenny, princess).
05 has_skill(jim, fly).
06 has_skill(jenny, invisibility).
07 pet(jim, horse).
08 pet(jenny, bird).
09 animal(horse).
10 animal(bird).
11 skill(fly).
12 skill(invisibility).
13 has_skill(X, Y) if character(X) and skill(Y).
TASK 3.1
TASK 3.2
Write a rule to state that a character can only have a pet, if they are a character, and the pet is an
animal.
TASK 3.3
TASK 3.4
• character(jim).
• character_type(jenny, X).
• character_type(X, prince).
• has_skill(jenny, X).
• has_skill(X, fly).
Permission to reproduce items where third-party owned material protected by copyright is included has been sought and cleared where possible. Every
reasonable effort has been made by the publisher (UCLES) to trace copyright holders, but if any items requiring clearance have unwittingly been included, the
publisher will be pleased to make amends at the earliest possible opportunity.
To avoid the issue of disclosure of answer-related information to candidates, all copyright acknowledgements are reproduced online in the Cambridge International
Examinations Copyright Acknowledgements Booklet. This is produced for each series of examinations and is freely available to download at www.cie.org.uk after
the live examination series.
Cambridge International Examinations is part of the Cambridge Assessment Group. Cambridge Assessment is the brand name of University of Cambridge Local
Examinations Syndicate (UCLES), which is itself a department of the University of Cambridge.
Write your Centre number, candidate number and name in the spaces at the top of this page.
Write in dark blue or black pen.
You may use an HB pencil for any diagrams, graphs or rough working.
Do not use staples, paper clips, glue or correction fluid.
DO NOT WRITE IN ANY BARCODES.
At the end of the examination, fasten all your work securely together.
The number of marks is given in brackets [ ] at the end of each question or part question.
DC (KN) 164472
© UCLES 2018 [Turn over
2
01 direct(edinburgh, paris).
02 direct(palma, rome).
03 direct(glasgow, palma).
04 direct(glasgow, vienna).
05 direct(glasgow, salzburg).
06
07 flies(paris, fly_jet).
08 flies(mumbai, british_air).
09 flies(palma, ciebe).
10 flies(vienna, fly_jet).
11 flies(salzburg, ciebe).
12
13 can_fly(X, Y) IF direct(X, Z) AND direct(Z, Y).
Clause Explanation
01 There is a direct route from Edinburgh to Paris.
07 Fly Jet operates flights to Paris.
13 It is possible to fly from X to Y if there is a direct flight from X to Z and a direct
flight from Z to Y.
There is a direct flight from London to Rome and British Air flies to Rome.
14 .............................................................................................................................................
15 .............................................................................................................................................
[2]
flies(Q, fly_jet).
returns
Q = paris, vienna
flies(K, ciebe).
K = ........................................................................................................................................[2]
(c) Use the variable M to write the goal to find where you can fly direct from Glasgow.
...............................................................................................................................................[2]
(d) If an airline flies to an airport, that airline also flies every direct route out of that airport.
flies(Y, X)
IF .............................................................................................................................................
...............................................................................................................................................[3]
can_fly(glasgow, rome).
...............................................................................................................................................[1]
2 The array ItemList[1:20] stores data. A bubble sort sorts these data.
01 MaxIndex 20
02 NumberItems ........................................................................................................
06 THEN
09 ItemList[Inner + 1] .............................................................
10 ENDIF
11 ENDFOR
12 NumberItems ..................................................................................................
13 ENDFOR
[7]
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[2]
(ii) Explain how you would improve the efficiency of this algorithm.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[3]
State two situations when an insertion sort is more efficient than a bubble sort. Give a reason
for each.
Situation 1 .................................................................................................................................
...................................................................................................................................................
Reason .....................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
Situation 2 .................................................................................................................................
...................................................................................................................................................
Reason .....................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
[4]
3 An internet based music streaming service provides access to an unlimited number of songs for
members to play.
CALL OpenAccount()
CALL OperateAccount()
CALL CloseAccount()
PROCEDURE OperateAccount()
WHILE RequestCloseAccount() = FALSE
IF SubscriptionDue() = TRUE
THEN
CALL MakePayment()
ELSE
CALL PlaySong()
ENDIF
ENDWHILE
ENDPROCEDURE
(a) Complete the JSP structure diagram for this music service from the pseudocode given.
Music Service
[5]
(b) The service needs extending so that members can download songs to play offline.
• When a member selects a song, the service checks if the song has already been
downloaded.
• If the member has already downloaded the song, the member has the option to delete or
play it.
• If the member has not already downloaded the song they have the option to download or
stream it.
Complete the following JSP structure diagram to represent these new requirements.
Select Song
[4]
4 A software company is developing a new application. The project manager has created a work
breakdown structure, as shown in the following table.
(a) Use the data in the table to complete the following Program Evaluation Review Technique
(PERT) chart.
........
........ ........ ........
........
........
[5]
5 A computer game is being developed using object-oriented programming. The following image is
a screenshot from the game.
There are scenery elements and animated elements. The player’s character is one of the animated
elements.
Each game element has a method, GetDetails() that returns a string containing all the
element’s attributes.
The player’s character is one of a number of animated elements. All animated elements have the
attributes:
GameElement AnimatedElement
PositionX: INTEGER AnimationFrames: ARRAY OF GameElement
PositionY: INTEGER
Width: INTEGER ...............................................................................
Height: INTEGER
ImageFilename: STRING ...............................................................................
...............................................................................
Constructor() Constructor()
GetDetails() AdjustHealth()
AdjustStrength()
DisplayAnimation()
Scenery Player
CauseDamage: BOOLEAN
DamagePoints: INTEGER
Constructor()
GiveDamagePoints() ...............................................................................
...............................................................................
...............................................................................
...............................................................................
[3]
Program code
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...............................................................................................................................................[6]
(c) The Scenery() class has two attributes, CauseDamage and DamagePoints.
If the attribute CauseDamage is TRUE, then the scenery element can cause damage.
The method GiveDamagePoints() checks whether the object can cause damage. If the
object can cause damage, the method returns the integer value of the DamagePoints
attribute.
Program code
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...............................................................................................................................................[6]
© UCLES 2018 9608/41/M/J/18 [Turn over
14
Attribute Value
PositionX 150
PositionY 150
Width 50
Height 75
ImageFilename "box.png"
CauseDamage TRUE
DamagePoints 50
Program code
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[3]
(ii) An additional method, GetScenery(), returns all the attributes of the Scenery class.
You should use the GetDetails() method that the Scenery class inherits from the
GameElement class.
Program code
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[3]
6 An Abstract Data Type (ADT) is used to create a linked list. The linked list is created as an array of
records. The records are of type ListNode.
(a) (i) Use pseudocode to write a definition for the record type, ListNode.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[3]
(ii) An array, Scorers, will hold 10 nodes of type ListNode. Use pseudocode to write an
array declaration for this array. The lower bound subscript is 0.
.......................................................................................................................................[2]
(b) The linked list stores ListNode records in alphabetical order of player. The last node in the
linked list always has a Pointer value of –1. The position of the first node in the linked list is
held in the variable ListHead.
After some processing, the array and variables are in the state as follows:
Scorers
ListHead Player Pointer
0 0 "Alvaro" 1
1 "Antoine" 3
2 "Dimitri" 7
3 "Cristiano" 2
4 "Gareth" 5
5 "Graziano" 6
6 "Olivier" 8
7 "Erik" 4
8 "Yaya" 9
9 "Zoto" -1
IF Scorer[Position].Player = ..............................................................................
THEN
RETURN ................................................................................................................
ELSE
IF Scorer[Position].Pointer <> –1
THEN
RETURN ...................................................................................................
ELSE
RETURN ...................................................................................................
ENDIF
ENDIF
ENDFUNCTION
[5]
14 direct(london, rome).
15 flies(rome, british_air).
K = palma, salzburg
direct(glasgow, M).
1(e) YES 1
e.g.
• When the list is almost sorted «
• «because it will stop as soon as it is sorted
• Downloaded?
• Download and Not downloaded beneath downloaded
• Delete song and play song beneath Downloaded (2) and Download song and stream song beneath not downloaded
• All selections correct
Select Song
Downloaded?
Not
Downloaded
Downloaded
Download
Delete Song Play Song Stream Song
Song
4(a) 1 ma
ark per bullet 5
• C
C, D and E all co
oming from 3
• G following D annd E
• F following C
• H from 6 to 7
• I from 7 to 8
4(b) 1 ma
ark per bullet 2
• AAÆBÆEÆGÆH HÆI
• 330 days
4(c) 1 ma
ark per bullet 2
• EEarliest start time: 19 days
• LLatest finish timee: 22 days
5(a) 1 ma
ark for each bulle
et: 3
• AnimatedElement attributes
A
• P
Player methods
• Inheritance arrow
ws
• class declaration
• private declaration of five attributes
• constructor declaration
• «initialisation of attributes to the parameter values
• declaration of GetDetails function
• appropriate concatenation of string using attributes
• return of all 5 values in one string
class GameElement:
def __init__(self, PositionX, PositionY, Width, Height,
ImageFilename):
self.__PositionX = PositionX
self. __PositionY = PositionY
self. __Width = Width
self. __Height = Height
self. __ImageFilename = String
def GetDetails(self):
Message = "Position_x:", self. __PositionX, "Position_y:", self. __PositionY,
"width:", self. __Width, "height:", self. __Height, "ImageFilename", self.
__ImageFilename)
return Message
Class GameElement
Private PositionX As Integer
Private PositionY As Integer
Private Width As Integer
Private Height As Integer
Private ImageFilename As String
End Class
private
PositionX : Integer;
PositionY : Integer;
Width : Integer;
Height : Integer;
ImageFilename : String;
public
Constructor init(X, Y, W, H:Integer; Filename: String);
Function GetDetails() : String;
end;
class Scenery(GameElement):
def __init__(self, PositionX, PositionY, Width, Height,
ImageFilename, CauseDamage, DamagePoints):
Object.__init__(self, PositionX, PositionY, Width, Height,
ImageFilename)
self.__CauseDamage = CauseDamage
self.__DamagePoints = DamagePoints
def GiveDamagePoints(self):
if(self.__CauseDamage):
return self.__DamagePoints
else:
return 0
Class Scenery
Inherits GameElement
Private CauseDamage As Boolean
Private DamagePoints As Integer
End Function
End Class
Scenery = class(GameElement)
private
CauseDamage : Boolean;
DamagePoints: Integer;
public
Constructor init(X, Y, W, H: Integer; Filename: String;
CD:Boolean; DP: Integer); override;
Function GiveDamagePoints() : Integer;
end;
constructor Scenery.init(X, Y, W, H: Integer; Filename: String; CD:
Boolean; DP: Integer);
begin
inherited init(X, Y, W, H, Filename);
CauseDamage := CD;
DamagePoints := DP;
end;
Function Scenery.GiveDamagePoints() : Integer;
begin
if (CauseDamage):
Result := DamagePoints
else:
Result := 0;
end;
def GetScenery(self):
Message = Object.GetDetails(self)
Message = Message + " Causes Damage:", self.CauseDamage, “Damage
Points:", self.DamagePoints
return Message
TYPE ListNode
DECLARE Player : STRING
DECLARE Pointer : INTEGER
ENDTYPE
Candidates should use this material in preparation for the examination. Candidates should attempt the
practical programming tasks using their chosen high-level, procedural programming language.
DC (LK) 148675/1
© UCLES 2018 [Turn over
2
Teachers and candidates should read this material prior to the November 2018 examination for 9608
Paper 4.
Reminders
• there will be questions on the examination paper which do not relate to this pre-release material
• you must choose a high-level programming language from this list:
Note: A mark of zero will be awarded if a programming language other than those listed is used.
The practical skills for Paper 4 build on the practical skills covered in Paper 2. We therefore recommend
that candidates choose the same high-level programming language for this paper as they did for
Paper 2. This will give candidates the opportunity for extensive practice and allow them to acquire
sufficient expertise.
• structured English
• pseudocode
• program code
Candidates will also benefit from using pre-release materials from previous examinations. These are
available on the teacher support site.
Declaration of variables
The syllabus document shows the syntax expected for a declaration statement in pseudocode.
If Python is the chosen language, each variable’s identifier (name) and its intended data type must be
documented using a comment statement.
Key focus:
TASK 1
Object-oriented programming
A computer shop sells different types of computer. Each type of computer performs different tasks.
The shop has a system to store and retrieve key information about the computers, so that customers
can find out more about them.
• The class MobilePhone is a type of computer, it has the properties of the Computer class, and:
• The class Laptop is a type of computer, it has the properties of the Computer class, and:
TASK 1.1
All of the properties are set to private. Check that you understand the difference between private and
public properties and why programmers use them.
TASK 1.2
Draw a class diagram for the Computer, MobilePhone and Laptop classes. Use the following
template to help you with this task.
Make sure you include the appropriate get and set methods. Key focus:
Defining classes
Computer
MobilePhone Laptop
TASK 1.3
Check that you understand the meaning of inheritance. The MobilePhone class and Laptop class
inherit from the Computer class.
TASK 1.4
TASK 1.5
Write program code to create the MobilePhone and Laptop classes. Make sure:
TASK 1.6
Add validation (where appropriate) to the constructor and set methods for all three classes. For
example, USB 3.0 ports might be limited to the range 0 to 6.
TASK 1.7
Create instances of the MobilePhone and Laptop classes with appropriate data in the main program.
Store the objects in arrays. To get you started, data for an instance of MobilePhone are as follows:
• Code = “MB1”
• Width = 6.2
• Height = 10.8 Key focus:
• Weight = 0.3
• Make = “camphones” Creating instances of classes
• Processor = “CIE234X”
• RAM size = “2GB”
• Storage size = “64GB”
• Camera = TRUE
• 3G = TRUE
• 4G = TRUE Key focus:
• Mobile Phone Network = “camNetwork”
Using objects in a program
TASK 1.8
Key focus:
TASK 2 Declarative language
A declarative language is used to create a set of facts and rules for a job agency.
01 job_status(sally, employed).
02 job_status(bill, unemployed).
03 first_aid_trained(sally).
04 first_aid_trained(bill).
05 years_experience(sally, 5).
06 years_experience(bill, 15).
07 qualified_as(sally, doctor).
08 qualified_as(bill, maths_teacher).
09 job_vacancy(autoshop, mechanic).
10 job_vacancy(a_school, maths_teacher).
11 suitable_job(X, Y) IF job_status(X, unemployed) AND qualified_as(X, Z)
AND job_vacancy(Y, Z).
TASK 2.1
TASK 2.3
• qualified_as(sally, B)
• job_vacancy(X, doctor)
• job_vacancy(a_school, art_teacher)
• suitable_job(joe, X)
TASK 2.5
An autoshop wants to hire a mechanic, with either at least five years’ experience or who is first aid
trained. Write a goal for this statement.
TASK 3
A program uses a record structure, Boat, to store information about boats. The record has the fields:
TASK 3.2
Write program code to declare your record structure. If you are using Python, you will need to create
a class.
TASK 3.3
TASK 3.5
Amend the program to allow a user to enter new boats. Each boat should be stored in the array.
TASK 3.6
Write a procedure to find and output the information about the boat the user has entered.
Write your Centre number, candidate number and name in the spaces at the top of this page.
Write in dark blue or black pen.
You may use an HB pencil for any diagrams, graphs or rough working.
Do not use staples, paper clips, glue or correction fluid.
DO NOT WRITE IN ANY BARCODES.
At the end of the examination, fasten all your work securely together.
The number of marks is given in brackets [ ] at the end of each question or part question.
DC (SC) 148677/4
© UCLES 2018 [Turn over
2
1 A declarative language is used to represent the following facts and rules about animals.
01 feature(dog, drinks_milk).
02 feature(dog, has_lungs).
03 feature(horse, has_lungs).
04 feature(tuna, lives_in_water).
05 feature(tuna, has_gills).
06 feature(crab, lives_in_water).
07 mammal(drinks_milk).
08 mammal(has_lungs).
09 fish(lives_in_water).
10 fish(has_gills).
Clause Explanation
01 A dog has the feature, drinks milk
07 A mammal drinks milk
11 X is a mammal, if:
• X has the feature Y and a mammal has a feature Y, and
• X has the feature Z and a mammal has the feature Z
12 ......................................................................................................................................
13 ......................................................................................................................................
[2]
14 ......................................................................................................................................
15 ......................................................................................................................................
[2]
feature(B, drinks_milk)
returns
B = dog
feature(B, lives_in_water)
B = .............................................................................................................................. [2]
(ii) Write a goal, using the variable C, to find the feature(s) of tuna.
...................................................................................................................................... [2]
is_a_bird(X) IF .................................................................................................................
.............................................................................................................................................. [3]
(d) Declarative programming and object-oriented programming are two examples of programming
paradigms.
...........................................................................................................................................
...................................................................................................................................... [1]
(ii) Give two examples of programming paradigms, other than declarative and object-oriented
programming.
1 ........................................................................................................................................
2 ........................................................................................................................................
[2]
2 Kendra collects books. She is writing a program to store and analyse information about her books.
Her program stores information about each book as a record. The following table shows the
information that will be stored about each book.
(a) Write pseudocode to declare an Abstract Data Type (ADT) named Book, to store the
information in the table.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [4]
The function, Hash(), takes as a parameter the ISBN and returns the hash value.
The disk address of the record in the hash table is calculated as: ISBN modulus 2000 plus 1.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [4]
(c) The random access file, MyBooks.dat, stores the data about the books in the format:
<Title>
<Author>
<ISBN>
<Fiction>
<LastRead>
A procedure, FindBook():
• rompts the user to input the ISBN of a book until the ISBN contains 13 numeric digits
p
• uses the function Hash() to calculate the disk address of the record
• reads the record for that book from MyBooks.dat into a variable of type Book
• outputs all the data about the book.
You can assume that the record exists at the disk address generated.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
© UCLES 2018 9608/41/O/N/18
7
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...............................................................................................................................................[8]
3 Joseph is taking a toy apart. Each time he removes an item from the toy, he writes the name of
the item at the bottom of a paper list. When he rebuilds the toy, he puts the items back together
working from the bottom of the list.
Joseph writes a computer program to create the list using a stack, Parts.
...................................................................................................................................................
.............................................................................................................................................. [1]
(b) The stack is represented as an array in the program, the first element in the array is [0].
The current contents of the stack, Parts, and its pointer, StackPointer are shown.
StackPointer 5 StackContents
0 "Screw 1"
1 "Screw 2"
2 "Back case"
3 "Screw 3"
4 "Engine outer"
5
6
7
...........................................................................................................................................
...................................................................................................................................... [1]
(ii) The procedure POP() removes an item from the stack. The procedure
PUSH(<identifier>) adds an item to the stack.
The current contents of the stack, Parts, and its pointer, StackPointer are shown.
StackPointer 5 StackContents
0 "Screw 1"
1 "Screw 2"
2 "Back case"
3 "Screw 3"
4 "Engine outer"
Use the table below to show the contents of the stack, Parts, and its pointer after the
following code is run.
POP()
POP()
PUSH("Light 1")
PUSH("Light 2")
PUSH("Wheel 1")
POP()
POP()
StackPointer StackContents
[2]
© UCLES 2018 9608/41/O/N/18 [Turn over
10
(c) A 1D array, Parts, is used to implement the stack. Parts is declared as:
(i) The procedure POP outputs the last element that has been pushed onto the stack and
replaces it with a '*'.
PROCEDURE POP
IF ………………………………. = ……………………………….
THEN
ELSE
StackPointer …………………………………………
OUTPUT ……………………………….……………………………….
Parts[StackPointer] ……………………………….
ENDIF
ENDPROCEDURE
[5]
(ii) The procedure PUSH() puts the parameter onto the stack.
THEN
ELSE
……………………….………..……… …………….………………….…..
StackPointer ………………………….….…………………………….
ENDIF
ENDPROCEDURE
[4]
02 IF Number = 0
03 THEN
04 Calculate −10
05 ELSE
07 ENDIF
08 ENDFUNCTION
...........................................................................................................................................
...................................................................................................................................... [1]
(ii) State the line number in Calculate() where the recursive call takes place.
...................................................................................................................................... [1]
Dry run the function and complete the trace table below. State the final value returned. Show
your working.
02 IF Number = 0
03 THEN
04 Calculate −10
05 ELSE
07 ENDIF
08 ENDFUNCTION
Working .....................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
Trace table:
(c) A recursive algorithm within a subroutine can be replaced with an iterative algorithm.
(i) Describe one problem that can occur when running a subroutine that has a recursive
algorithm.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [2]
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [5]
5 A game uses a set of cards. Each card has a number (between 0 and 9 inclusive) and a shape
("square", "triangle" or "circle").
• Number
• Shape
• Constructor()
• GetNumber()
• GetShape()
The purpose of each method in the class Cards is given in the following table.
Method Purpose
Constructor() Takes a number and a shape as parameters
Checks that the number and the shape are valid and:
• either assigns the parameters to Number and Shape
• or reports an error.
GetNumber() A public method that returns the number for that card.
GetShape() A public method that returns the shape for that card.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [2]
Program code
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [5]
Program code
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [2]
(d) A card, OneS, has the value 1 for Number and the value "square" for Shape.
Program code
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [2]
© UCLES 2018 9608/41/O/N/18 [Turn over
16
(e) The game has a function, Compare() that takes two cards as parameters and compares
them.
If the cards are identical, the function outputs "SNAP" and returns −1. If they are not identical,
and the card numbers are different, it returns the Number of the card with the higher value or
the Number for the cards if they are the same.
Program code
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [6]
Permission to reproduce items where third-party owned material protected by copyright is included has been sought and cleared where possible. Every
reasonable effort has been made by the publisher (UCLES) to trace copyright holders, but if any items requiring clearance have unwittingly been included, the
publisher will be pleased to make amends at the earliest possible opportunity.
To avoid the issue of disclosure of answer-related information to candidates, all copyright acknowledgements are reproduced online in the Cambridge International
Examinations Copyright Acknowledgements Booklet. This is produced for each series of examinations and is freely available to download at www.cie.org.uk after
the live examination series.
Cambridge International Examinations is part of the Cambridge Assessment Group. Cambridge Assessment is the brand name of University of Cambridge Local
Examinations Syndicate (UCLES), which is itself a department of the University of Cambridge.
• bird(lays_egg).
• bird(has_wings).
• feature(eagle, lays_eggs).
• feature(eagle, has_wings).
tuna, crab
• feature()
• tuna, C
feature(tuna, C)
• Low-level
• Imperative // Procedural
For example:
TYPE Book
DECLARE Title : String
DECLARE Author : String
DECLARE ISBN : String
DECLARE Fiction : Boolean
DECLARE LastRead : Date
ENDTYPE
• Function header
• « taking ISBN as parameter
• Converting ISBN to integer
• Calculating Hash (ISBN mod 2000 + 1)
• Returning the calculated Hash
Examples:
Python:
def Hash(ISBN):
ISBNint = int(ISBN)
Hash = (ISBNint % 2000) + 1
VB.NET:
Pascal:
2(c) Example:
PROCEDURE FindBook()
DECLARE BookInfo : Book
REPEAT
ISBN ← input("Enter the ISBN number")
Valid ← TRUE
Size ← LENGTH(ISBN)
IF size <> 13
THEN
Valid ← FALSE
ELSE
FOR i ← 1 to 13
IF NOT( MID(ISBN,i,1) >= '0' AND MID(ISBN,i,1)<= '9' )
THEN
Valid ← FALSE
ENDIF
ENDFOR
ENDIF
UNTIL Valid
Filename ← "myBooks.dat"
OPENFILE Filename FOR RANDOM
RecordLocation ← Hash(ISBN)
SEEK FileName, RecordLocation
GETRECORD Filename, BookInfo
CLOSEFILE Filename
OUTPUT (BookInfo.Title & " " & BookInfo.Author & " " &
BookInfo.ISBN & " " & BookInfo.Fiction & " " &
BookInfo.LastRead)
ENDPROCEDURE
StackPointer 4 StackContents
0 "Screw 1"
1 "Screw 2"
2 "Back case"
3 "Light 1"
PROCEDURE POP
IF StackPointer = 0
THEN
OUTPUT ("The stack is empty")
ELSE
StackPointer ← StackPointer - 1
OUTPUT Parts[StackPointer]
Parts(StackPointer) ← "*"
ENDIF
ENDPROCEDURE
4(a)(ii) 06 1
• Each time it calls itself the variables are put onto the stack // The function call itself too many times
• « it runs out of stack space // stack overflow
For example:
RETURN Value
ENDFUNCTION
• To restrict direct access to the property to the class // keep the properties secure // So the data can only be accessed
by its methods // makes the program more robust
• To make the program easier to debug
• To ensure data going in is valid // to stop invalid changes // stop accidental changes
• Constructor method header taking 2 parameters (with correct data types if given)
• Checking if Number > = 0 and < = 9
• Checking theShape is ‘square’ or ‘triangle’ or ‘circle’
• « if both valid assigning Number and Shape the parameters
• « if either invalid report error (output/returning value/catching error)
5(b) Examples:
Python
VB.NET
Pascal
Examples:
Python
def GetNumber():
return(self.__Number)
VB.NET
Pascal
Examples:
Python
VB.NET
Pascal
5(e) Examples:
Python
VB.NET
Console.writeline("SNAP")
Return -1
ELSEIF P2Card.GetNumber() > P1Card.GetNumber() THEN
P2Card.GetNumber()
ELSE
Return P1Card.GetNumber()
ENDIF
End Function
5(e) Pascal
Candidates should use this material in preparation for the examination. Candidates should attempt the
practical programming tasks using their chosen high-level, procedural programming language.
DC (KS) 180307
© UCLES 2019 [Turn over
2
Teachers and candidates should read this material prior to the June 2019 examination for 9608 Paper 4.
Reminders
• there will be questions on the examination paper which do not relate to this pre-release material
• you must choose a high-level programming language from this list:
Note: A mark of zero will be awarded if a programming language other than those listed is used.
The practical skills for Paper 4 build on the practical skills covered in Paper 2. We therefore recommend
that candidates choose the same high-level programming language for this paper as they did for Paper
2. This will give candidates the opportunity for extensive practice and allow them to acquire sufficient
expertise.
• structured English
• pseudocode
• program code
Candidates will also benefit from using pre-release materials from previous examinations.
Declaration of variables
The syllabus document shows the syntax expected for a declaration statement in pseudocode.
If Python is the chosen language, each variable’s identifier (name) and its intended data type must be
documented using a comment statement.
TASK 1.1
A binary tree is a type of data structure. In a binary tree, each node will have up to two connected
nodes. These connected nodes are called child nodes. Each parent node can have a left child node
and a right child node. For example:
Parent node
21
Create a random list of 10 items of data about your favourite hobby or topic, for example, 10 different
types of bird.
Create a binary tree for the list of items. Add items to the tree in ascending alphabetical order, 'a' to
'z'.
TASK 1.2
It is possible to represent data in a binary tree as a linked list of nodes. Each node can have a left
pointer and a right pointer. For example:
Root pointer
15 26
Whenever a node does not have a child node, the relevant pointer stores a null symbol, such as the
symbol ∅. For example, in our previous tree that has two childless, leaf nodes:
Root pointer
∅ 15 ∅ ∅ 26 ∅
Root pointer
15 ∅ 26
∅ 4 ∅ ∅ 24 ∅ ∅ 29 ∅
In TASK 1.1, you added your 10 items to a binary tree. Now redraw your tree as a linked list of nodes.
Use the correct pointer value wherever the node has no child.
TASK 1.3
The data in the linked list binary tree at the end of TASK 1.2 are suitable for storage in a 2D array.
We can represent the 2D array for the numerical data as a table. For example:
0 0 21
1 15
2 26
3 4
FreePointer
4 24
5 29
6
The left and right pointer can be completed in the table. The other pointers are completed by assigning
the right pointer of the node first, and then left. The free pointer is then assigned the position of the next
available array index. For example:
6 5 ∅ 29 ∅
6
Create a table to represent an array of records for your linked list binary tree, completing the left, right
and free pointers.
TASK 1.4
Create a program in the language of your choice that adds an item of data to a list.
TASK 2 - Stacks
A stack is an Abstract Data Type (ADT) that stores a collection of data. It has two operations that
manipulate its data:
TASK 2.1
26
15
21
PUSH(4)
POP()
POP()
PUSH(24)
PUSH(29)
Draw a representation to show what the stack would look like after the commands have been carried
out.
TASK 2.2
Write a program in the language of your choice to add and remove items of data from a stack.
Write your centre number, candidate number and name in the spaces at the top of this page.
Write in dark blue or black pen.
You may use an HB pencil for any diagrams, graphs or rough working.
Do not use staples, paper clips, glue or correction fluid.
DO NOT WRITE IN ANY BARCODES.
At the end of the examination, fasten all your work securely together.
The number of marks is given in brackets [ ] at the end of each question or part question.
DC (PQ) 180360
© UCLES 2019 [Turn over
2
1 (a) A stack contains the values 'red', 'blue', 'green' and 'yellow'.
(i) Show the contents of the stack in part(a) after the following operations.
POP()
PUSH('purple')
PUSH('orange')
[1]
(ii) Show the contents of the stack from part(a)(i) after these further operations.
POP()
POP()
PUSH('brown')
POP()
PUSH('black')
[1]
Describe a queue.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [3]
2 A computer games club wants to run a competition. The club needs a system to store the scores
achieved in the competition.
(a) A linked list of nodes will be used to store the data. Each node consists of the data, a left
pointer and a right pointer. The linked list will be organised as a binary tree.
(i) Complete the binary tree to show how the score data above will be organised.
RootPointer
The symbol ∅ represents a null pointer.
LeftPointer RightPointer
99
97 ∅ 125
121
[5]
© UCLES 2019 9608/41/M/J/19
5
(ii) The following diagram shows a 2D array that stores the nodes of the binary tree’s linked
list.
Add the correct pointer values to complete the diagram, using your answer from
part (a)(i).
0 0 99
1 125
2 121
3 97
FreePointer
4 109
5 95
6 135
7 149
[6]
(b) The club also considers storing the data in the order in which it receives the scores as a
linked list in a 1D array of records.
The following pseudocode algorithm searches for an element in the linked list.
…………………………………………… ← RootPointer
THEN
CurrentPointer ← List[……………………………………………].Pointer
ELSE
RETURN CurrentPointer
ENDIF
ENDWHILE
CurrentPointer ← NullPointer
………………………………………… CurrentPointer
ENDFUNCTION
[6]
(c) The games club is looking at two programming paradigms: imperative and object-oriented
programming paradigms.
Describe what is meant by the imperative programming paradigm and the object-oriented
programming paradigm.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [3]
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [3]
(d) Players complete one game to place them into a category for the competition. The games club
wants to implement a program to place players into the correct category. The programmer
has decided to use object-oriented programming (OOP).
The highest score that can be achieved in the game is 150. Any score less than 50 will not
qualify for the competition. Players will be placed in a category based on their score.
The following diagram shows the design for the class Player. This includes the properties
and methods.
Player
Score : INTEGER // initialised to 0
Category : STRING // "Beginner", "Intermediate",
// "Advanced" or "Not Qualified", initialised
// to "Not Qualified"
PlayerID : STRING // initialised with the parameter InputPlayerID
(i) The constructor receives the parameter InputPlayerID to create the PlayerID.
Other properties are initialised as instructed in the class diagram.
Program code
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [5]
(ii) Write program code for the following three get methods.
GetScore()
Program code
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
GetCategory()
Program code
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
GetPlayerID()
Program code
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
[4]
(iii) The method SetPlayerID()asks the user to input the new player ID and reads in this
value.
It checks that the length of the PlayerID is less than or equal to 15 characters and
greater than or equal to 4 characters. If the input is valid, it sets this as the PlayerID,
otherwise it loops until the player inputs a valid PlayerID.
Program code
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [4]
(iv) The method SetScore()checks that its INTEGER parameter ScoreInput is valid. If
it is valid, it is then set as Score. A valid ScoreInput is greater than or equal to 0 and
less than or equal to 150.
If the ScoreInput is valid, the method sets Score and returns TRUE.
If the ScoreInput is not valid, the method does not set Score, displays an error
message, and it returns FALSE.
Program code
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [5]
(v) Write program code for the method SetCategory(). Use the properties and methods
in the original class definition.
Category Criteria
Program code
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [4]
(vi) Joanne has played the first game to place her in a category for the competition.
Program code
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [8]
(e) The programmer wants to test that the correct category is set for a player’s score.
As stated in part (d)(v), players will be placed in one of the following categories.
Category Criteria
Beginner Abnormal
Boundary
Normal
Intermediate Abnormal
Boundary
Normal
Advanced Abnormal
Boundary
[3]
(f) In part (b), the club stored scores in a 1D array. This allows the club to sort the scores.
NumberOfScores ← 5
InsertScore ← ArrayData[Item]
Index ← Item – 1
ArrayData[Index + 1] ← ArrayData[Index]
Index ← Index – 1
ENDWHILE
ArrayData[Index + 1] ← InsertScore
ENDFOR
..................................................................................................................................... [1]
..................................................................................................................................... [1]
(iii) Complete a dry run of the algorithm using the following trace table.
ArrayData
Item NumberOfScores InsertScore Index
0 1 2 3 4
99 125 121 109 115
[7]
Feature 1 ...................................................................................................................................
Feature 2 ...................................................................................................................................
[2]
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [3]
orange
purple
green
blue
red
black
green
blue
red
RootPointer
LeftPointer RightPointer
99
97 Ø 125
Ø 95 Ø 121 Ø Ø 135
Ø 109 Ø Ø 149 Ø
• FreePointer as 8
• 99
• 125
• 121 and 97
• 109 and 95
• 135 and 149
0 [0] 3 99 1
[1] 2 125 6
8 [3] 5 97 null
[8]
PYTHON
def__init__(self, InputPlayerID):
self.__Score = 0
self.__Category = "Not Qualified"
self.__PlayerID = InputPlayerID
PASCAL
Constructor Player.Create(InputPlayerID);
begin
Score := 0 ;
Category := 'Not Qualified' ;
PlayerID := InputPlayerID;
end;
VB
Public Sub New (InputPlayerID)
Score = 0
Category = "Not Qualified"
PlayerID = InputPlayerID
End Sub
• 1 get Method header without parameter (returning correct data type if given)
• «returning the property
• A second working Get
• A third working Get
PYTHON
def GetScore():
return (Score)
def GetCategory():
return (Category)
def GetPlayerID():
return (PlayerID)
PASCAL
function GetScore():Integer;
begin
GetScore:= Score;
end;
function GetCategory():String;
begin
GetCategory:= Category;
end;
function GetPlayerID():String;
begin
GetPlayerID:= PlayerID;
end;
VB
Public Function GetScore() As Integer
Return Score
End Function
Public Function GetCategory() As String
Return Category
End Function
Public Function GetPlayerID() As String
Return PlayerID
End Function
PYTHON
def SetPlayerID(self)
PlayerID = input("Enter your player ID")
while len(PlayerID) > 15 and len(PlayerId) < 4
PlayerID = input("Must be <=15 AND >=4 characters long.
Enter your player ID")
PASCAL
Procedure SetPlayerID ()
WriteLn ('Enter your player ID');
ReadLn(PlayerID);
while length(PlayerID) > 15 and length(PlayerID) < 4 do
begin
WriteLn('Must be <=15 AND >=4 characters long. Enter
your player ID');
ReadLn(PlayerID);
end;
VB
Public Sub SetPlayerID()
Console.WriteLine ("Enter your player ID")
PlayerID = Console.ReadLine()
While Len(PlayerID) > 15 and Len(PlayerID) < 4
Console.WriteLine ("Must be <=15 AND >=4 characters
long. Enter your player ID")
PlayerID = Console.ReadLine()
End While
End Sub
PYTHON
def __SetScore(ScoreInput):
if ScoreInput >=0 and ScoreInput <=150:
IsValid = True
self__Score = ScoreInput
else:
print("Error")
IsValid = False
Return(IsValid)
PASCAL
function Player.SetScore(ScoreInput: Integer) : Boolean;
begin
If (ScoreInput >=0) AND (ScoreInput <=150) Then
IsValid := True;
result := ScoreInput;
Else
WriteLn('Error')
result := False;
end;
VB
Public Function SetScore(ByVal ScoreInput As Integer) As
Boolean
If (ScoreInput >=0) And (ScoreInput <=150) Then
Return True
Score = ScoreInput
Else
Console.Writeline("Error")
Return False
End If
End Function
PYTHON
def SetCategory()
if self.__Score >120:
self.__Category = "Advanced"
elif self.__Score >80:
self.__Category = "Intermediate"
elif self.__Score>=50:
self.__Category = "Beginner"
else:
self.__Category = "Not Qualified"
PASCAL
procedure player.SetCategory()
begin
If Score >120 Then
Category := "Advanced";
Else If Score >80 Then
Category := "Intermediate";
Else If Score >= 50 Then
Category := "Beginner";
Else
Category := "Not Qualified";
end;
VB
Public Sub SetCategory()
If Score >120 Then
Category = "Advanced"
ElseIf Score >80 Then
Category = "Intermediate"
ElseIf Score >=50 Then
Category = "Beginner"
Else
Category = "Not Qualified"
End If
End Sub
PYTHON
def CreatePlayer():
InputPlayerID = input("Enter your chosen ID")
Score = int(input("Please enter the score"))
JoannePlayer = Player(InputPlayerID)
if JoannePlayer.SetScore(Score) == false:
print("Invalid score")
else:
JoannePlayer.SetCategory()
print(JoannePlayer.GetCategory)
PASCAL
procedure CreatePlayer();
var
playerID : String;
isValid : boolean;
JoannePlayer : Player;
score : integer;
begin
Writeln(Enter Player ID: ');
Readln(playerID);
Writeln('Enter score: ');
Readln(score);
JoannePlayer := Player.Create(PlayerID);
isValid := JoannePlayer.SetScore(Score);
if isValid = true:
JoannePlayer.SetCategory();
Writeln(JoannePlayer.GetCategory());
else:
Writeln("Invalid score")
end;
2(d)(vi) VB
Sub CreatePlayer()
Dim Score As Integer, InputPlayerID As String
Console.WriteLine("Please enter your chosen ID")
InputPlayerID = Console.ReadLine()
Console.WriteLine("Please enter the score")
Score = Console.ReadLine()
Boundary 80, 50
ArrayData
Item NumberOfScores InsertScore Index
0 1 2 3 4
1 5 125 0 (125)
2 121 1 125
0 121
3 109 2 125
1 121
0 109
4 115 3 125
2 121
1 115