Sunteți pe pagina 1din 337

Cambridge International Examinations

Cambridge International Advanced Subsidiary and Advanced Level

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.

Questions on the examination paper may ask the candidate to write:


• structured English
• pseudocode
• program code

A program flowchart should be considered as an alternative to pseudocode for the documenting of an


algorithm design.

Candidates should be confident with:


• the presentation of an algorithm using either a program flowchart or pseudocode
• the production of a program flowchart from given pseudocode (or the reverse)

© UCLES 2015 9608/41/PRE/M/J/15


3

TASK 1

A linked list Abstract Data Type (ADT) has these associated operations:

• create linked list


• add item to linked list Key focus: Linked lists
• remove item from linked list

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.

The following sequence of operations is carried out:

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:

© UCLES 2015 9608/41/PRE/M/J/15 [Turn over


4

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.

Key focus: Implementation of


linked lists using an array of records

NameList
HeadPointer Name Pointer
[1]

[2]

[3]

[4]

[5]

FreePointer [6]

[49]

[50]

Write pseudocode for the CreateLinkedList operation.

Write program code from your pseudocode design.

© UCLES 2015 9608/41/PRE/M/J/15


5

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]

© UCLES 2015 9608/41/PRE/M/J/15 [Turn over


6

TASK 1.4
Complete the identifier table for the pseudocode given below.

Identifier Data type Description


Array to store node data
Name to be added
Pointer to next free node in array
Pointer to first node in list
Pointer to current node
Pointer to previous node
Pointer to new node

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

© UCLES 2015 9608/41/PRE/M/J/15


7

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:

If list is not empty


Find the name to be removed
If it is the first name in the linked list
Adjust the head pointer
If it is not the first name in the linked list
Adjust pointers to exclude the name to be removed from the list
Link released node into free list

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.

Suggested extension task


Queues, stacks, binary trees and dictionaries can be implemented as linked lists of nodes.

Design pseudocode and write program code for these data structures.

© UCLES 2015 9608/41/PRE/M/J/15 [Turn over


8

TASK 2

A vehicle hire company has cars and trucks for hire.

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.

© UCLES 2015 9608/41/PRE/M/J/15


9

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.

Suggested extension task


Write program code to display the properties of the object you created in Task 2.4.

© UCLES 2015 9608/41/PRE/M/J/15 [Turn over


10

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.

Current state Event Next state


System inactive Switch power on System active
System active Senses intruder Alarm bell rings
System active Switch power off System inactive
Alarm bell rings Press reset button System active
Alarm bell rings Switch power off System inactive

Key focus: State transition diagrams


Complete the diagram.

..............................
start

.............................. ..............................

..............................

..............................

.............................. ..............................

..............................

© UCLES 2015 9608/41/PRE/M/J/15


Cambridge International Examinations
Cambridge International Advanced Level
* 7 9 0 6 0 4 9 1 7 9 *

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills May/June 2016
2 hours
Candidates answer on the Question Paper.
No Additional Materials are required.
No calculators allowed.

READ THESE INSTRUCTIONS FIRST

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.

Answer all questions.

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.

The maximum number of marks is 75.

This document consists of 19 printed pages and 1 blank page.

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.

Identifier Data type Description


LinkedList RECORD User-defined type
Surname STRING Surname string
Ptr INTEGER Link pointers for the linked list

(a) (i) Write pseudocode to declare the type LinkedList.

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.......................................................................................................................................[3]

(ii) The 1D array is implemented with an array SurnameList of type LinkedList.

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 …

State the value of the following:

(i) SurnameList[4].Surname .......................................................................................[1]

(ii) SurnameList[StartPtr].Ptr ................................................................................[1]

© UCLES 2016 9608/41/M/J/16


3

(c) Pseudocode is to be written to search the linked list for a surname input by the user.

Identifier Data type Description


ThisSurname STRING The surname to search for
Current INTEGER Index to array SurnameList
Index to array SurnameList. Points to the
StartPtr INTEGER
element at the start of the linked list

(i) Study the pseudocode in part (c)(ii).

Complete the table above by adding the missing identifier details. [2]

(ii) Complete the pseudocode.

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]

© UCLES 2016 9608/41/M/J/16 [Turn over


4

2 (a) (i) State what is meant by a recursively defined procedure.

...........................................................................................................................................

.......................................................................................................................................[1]

(ii) Write the line number from the pseudocode shown in part (b) that shows the

procedure X is recursive. .............................. [1]

(b) The recursive procedure X is defined as follows:

01 PROCEDURE X(Index, Item)


02 IF MyList[Index] > 0
03 THEN
04 IF MyList(Index) >= Item
05 THEN
06 MyList[Index] ← MyList[Index + 1]
07 ENDIF
08 CALL X(Index + 1, Item)
09 ENDIF
10 ENDPROCEDURE

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

© UCLES 2016 9608/41/M/J/16


5

(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]

© UCLES 2016 9608/41/M/J/16 [Turn over


6

3 A car hire company hires cars to customers. Each time a car is hired, this is treated as a transaction.

For each transaction, the following data are stored.

For the customer:

• customer name
• ID number

For the hire:

• 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.

F_BODY has one transaction, TRANS, on each line.

(a) The first step in Jackson Structured Programming (JSP) design is to produce a JSP data
structure diagram.

Complete the following JSP data structure diagram.

HIRE-TRANS

F_BODY

[7]
© UCLES 2016 9608/41/M/J/16
7

(b) The computer system will produce many printed reports.

One report is CAR_REPORT. This displays all hire data for all cars.

For each car, the following data are displayed:

• the car data


• a list of all the hires
• the total number of hires

A car with zero hires is not included on the report.

Complete the following CAR_REPORT JSP data structure diagram.

CAR_REPORT

*
CAR

No hires One or more hires

HIRE_LIST

HIRE

[5]

© UCLES 2016 9608/41/M/J/16 [Turn over


8

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.

Cars have a unique three-character registration.

The following knowledge base is used:

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.

(a) (i) DeadlineYear is assigned value 2011.

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]

© UCLES 2016 9608/41/M/J/16


9

(b) If a car fails one of the two tests, a retest is allowed.

Write a new rule for this.

retestAllowed(..............................) if ............................................................................

...................................................................................................................................................

...............................................................................................................................................[3]

(c) Logic programming uses a data structure called a list.

A new fact is added to the knowledge base.

23 carList = [a03,p05,b04,h04,h07,a23].

The following notation and operators are to be used with a list:

[X|Y] denotes a list with:

• X the first list element


• Y the list consisting of the remaining list elements

[] denotes an empty list

(i) The list [a07,p03] is denoted by [A|B]

State the value of A and B.

A = ......................................................................................

B = ...................................................................................... [2]

(ii) The lists [c03,d02,n05|C] and [c03,d02,n05,p05,m04] are identical.

State the value of C.

C = ..................................................................................... [1]

(iii) The list [a06,a02] is denoted by [D,E|F]

State the value of F.

F = ..................................................................................... [1]

© UCLES 2016 9608/41/M/J/16 [Turn over


10

(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.

If equal, the clause evaluates to TRUE, otherwise FALSE.

Consider the clause:

conCatCompare(X, Y, [a7,b6,c4])

If:

• the clause evaluates to TRUE


• and Y represents the list [a7, b6, c4]

State the value of X.

X = .................................................................................................................................[1]

© UCLES 2016 9608/41/M/J/16


11

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:

• has a single parameter Mark of INTEGER data type


• returns the grade awarded Grade of STRING data type

The logic for calculating the grade is as follows:

Mark Grade
Under 40 FAIL
40 and over and under 55 PASS
55 and over and under 70 MERIT
70 and over DISTINCTION

The programmer designs the following table for test data:

Mark Description Expected result (Grade)


Normal
Abnormal
Extreme/Boundary

(i) Complete the table above. [3]

(ii) State why this table design is suitable for black box testing.

...........................................................................................................................................

.......................................................................................................................................[1]

© UCLES 2016 9608/41/M/J/16 [Turn over


12

(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]

© UCLES 2016 9608/41/M/J/16


13

(d) The following pseudocode is to read two numbers:

01 DECLARE Num1 : INTEGER


02 DECLARE Num2 : INTEGER
03 DECLARE Answer : INTEGER
04 TRY
05 OUTPUT "First number..."
06 INPUT Num1
07 OUTPUT "Second number..."
08 INPUT Num2
09 Answer ← Num1 / (Num2 – 6)
10 OUTPUT Answer
11 EXCEPT ThisException : EXCEPTION
12 OUTPUT ThisException.Message
13 FINALLY
14 // remainder of the program follows

29
30 ENDTRY

The programmer writes the corresponding program code.

A user inputs the number 53 followed by 6. The following output is produced:

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]

(ii) Explain the purpose of the pseudocode on lines 11 and 12.

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.......................................................................................................................................[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.

The game ends if:

• 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’.

(a) A state-transition diagram is drawn to clarify how the game is played.

Complete the following state-transition diagram.

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:

'B' represents a black piece


'W' represents a white piece
'E' represents an empty 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.

Programming language .....................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.......................................................................................................................................[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.

This will be a move:

• either to an empty square, with no occupied squares on the way

• or to a square containing a piece belonging to another player, with no occupied


squares on the way. The other player’s piece is then removed.

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

2 It needs three parameters:

3 • PieceColour – colour of the moving piece


• xCurrent – current x position
4 • yCurrent – current y position
5 The procedure will calculate all possible destination
squares in the x direction only.
6

Example output for the circled black piece is:

Possible moves are:


Moving LEFT
3 4
2 4 REMOVE piece
Moving RIGHT
5 4
6 4
7 4

Write program code for procedure ValidMoves with the following procedure header:

PROCEDURE ValidMoves(PieceColour : CHAR, xCurrent : INTEGER,


yCurrent : INTEGER).

© UCLES 2016 9608/41/M/J/16


17

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.

Programming language .....................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................
© UCLES 2016 9608/41/M/J/16 [Turn over
18

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

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

© UCLES 2016 9608/41/M/J/16


19

(c) The problem is well suited to an object-oriented design followed by object-oriented


programming.

(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]

© UCLES 2016 9608/41/M/J/16


Page 2 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2015 9608 41

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).

accept in any order [4]

(b) ThisCity =
manchester
london [2]

(c) countries_visited(ThisCountry)
IF
city_visited(ThisCity) 1
AND 1
city_in_country(ThisCity, ThisCountry) 2 [4]

© Cambridge International Examinations 2015


Page 3 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2015 9608 41

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

have discount card Y N Y N Y N Y N

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

have discount card Y N Y N -

No discount X X
Actions

5% discount X X

10% discount X

1 mark per column [5]

© Cambridge International Examinations 2015


Page 4 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2015 9608 41

(c) Example Pascal

FUNCTION Discount(GoodsTotal: INTEGER; HasDiscountCard: BOOLEAN) :


INTEGER;

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

def Discount(GoodsTotal, HasDiscountCard) :

(1) if GoodsTotal > 20:


(2) if GoodsTotal > 100:
(3) if HasDiscountCard == True:
(3) return 10
(3) else:
(3) return 5
(2) else:
(4) if HasDiscountCard == TRUE:
(4) return 5
(4) else:
(4) return 0
(1) else:
(1) return 0 [6]

© Cambridge International Examinations 2015


Page 5 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2015 9608 41

4 (a)

[3]

© Cambridge International Examinations 2015


Page 6 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2015 9608 41

(b) Example Pascal


Type
Employee = CLASS
PUBLIC
procedure SetEmployeeName
Procedure SetEmployeeID
Procedure CalculatePay
PRIVATE
EmployeeName : STRING
EmployeeID : STRING
AmountPaidThisMonth : Currency
END;

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]

© Cambridge International Examinations 2015


Page 7 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2015 9608 41

(c) (i) HoursWorked 1


HourlyPayRate 1
SetHoursWorked 1
CalculatePay : Override 1+1
SetPayRate 1 [max 4]

(ii) AnnualSalary 1
SetSalary 1
CalculatePay : Override 1 [max 2]

(d) Polymorphism [1]

5 (a) (i) FOR ThisPointer  2 TO 10


// use a temporary variable to store item which is to
// be inserted into its correct location
Temp  NameList[ThisPointer]
Pointer  ThisPointer – 1

WHILE (NameList[Pointer] > Temp) AND (Pointer > 0)


// move list item to next location
NameList[Pointer + 1]  NameList[Pointer]
Pointer  Pointer - 1
ENDWHILE

// insert value of Temp in correct location


NameList[Pointer + 1] Temp
ENDFOR
1 mark for each gap filled correctly [7]

(ii) The outer loop (FOR loop) is executed 9 times (1 mark)


it is not dependant on the dataset (1 mark)

The Inner loop (WHILE loop) is not entered (1 mark)


as the condition is already false at the first encounter (1 mark) [max 3]

(b) (i) outer loop is executed 9 times (1 mark)


inner loop is executed 9 times (for each iteration of the outer loop) (1 mark)
not dependant on the dataset (1 mark) [max 2]

© Cambridge International Examinations 2015


Page 8 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2015 9608 41

(ii) NumberOfItems  10
REPEAT
NoMoreSwaps  TRUE

FOR Pointer  1 TO NumberOfItems – 1


IF NameList[Pointer] > NameList[Pointer + 1]
THEN
NoMoreSwaps  FALSE
Temp  NameList[Pointer]
NameList[Pointer]  NameList[Pointer + 1]
NameList[Pointer + 1]  Temp
ENDIF
ENDFOR
NumberOfItems  NumberOfItems - 1
UNTIL 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

1 mark for Head and Tail pointers


1 mark for 3 correct items – linked as shown
1 mark for correct order with null pointer in last nod [3]

© Cambridge International Examinations 2015


Page 9 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2015 9608 41

(b) (i)
Queue

HeadPointer Name Pointer

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:

HeadPointer =0 & TailPointer = 0


FreePointer assigned a value
Pointers[1] to [9] links the nodes together
Pointer[10] = 'Null' [4]

(ii) PROCEDURE RemoveName()


// Report error if Queue is empty
IF HeadPointer = 0
THEN
Error
ELSE
OUTPUT Queue[HeadPointer].Name
// current node is head of queue
CurrentPointer  HeadPointer
// update head pointer
HeadPointer  Queue[CurrentPointer].Pointer
//if only one element in queue,then update tail pointer
IF HeadPointer = 0
THEN
TailPointer  0
ENDIF
// link released node to free list
Queue[CurrentPointer].Pointer  FreePointer
FreePointer  CurrentPointer
ENDIF
ENDPROCEDURE [max 6]

© Cambridge International Examinations 2015


Cambridge International Examinations
Cambridge International Advanced Level

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills October/November 2015
PRE-RELEASE MATERIAL
* 9 7 3 2 7 4 1 0 7 0 *

This material should be given to candidates on receipt by the Centre.

READ THESE INSTRUCTIONS FIRST

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.

This document consists of 9 printed pages and 3 blank pages.

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.

Questions on the examination paper may ask the candidate to write:


• structured English
• pseudocode
• program code

A program flowchart should be considered as an alternative to pseudocode for the documenting of an


algorithm design.

Candidates should be confident with:


• the presentation of an algorithm using either a program flowchart or pseudocode
• the production of a program flowchart from given pseudocode or the reverse

© UCLES 2015 9608/41/PRE/O/N/15


3

TASK 1

The taxis used by a taxi company are either cars or minibuses.

The unique registration and the charge (in $) per unit time are stored for all taxis.

All cars can carry a maximum of four passengers.

Data stored about minibuses also includes an extra charge (in $) per booking and the maximum
number of passengers allowed.

The company needs software to process data about taxis.

The processing needs to include a calculation of the fare charged.

The software will be object-oriented.

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.

© UCLES 2015 9608/41/PRE/O/N/15 [Turn over


4

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.

Suggested extension task


Write program code to display the properties of the object you created in Task 1.4.

© UCLES 2015 9608/41/PRE/O/N/15


5

TASK 2

Key focus: Project management using


PERT and GANTT charts
A software program is to be written for a client.

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.

Integration testing is expected to take 3 hours and Alpha testing 7 hours.

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.

Complete the diagram below.

1 3 4 5

2
Key focus: Project management
using a PERT chart

Note: the arrow denotes a dummy activity.

Write the critical path.

Calculate the shortest time (in days) before the client can start acceptance testing.

© UCLES 2015 9608/41/PRE/O/N/15 [Turn over


6

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.

Suggested extension task


Try other proposals, such as only a software tester can carry out any testing.
Activity
Code P1
Test P1
Code P2
Test P2
Code P3
Test P3
Code P4
Test P4
Code P5
Test P5
Code P6
Test P6
Code P7
Test P7
Code P8
Test P8
Integration testing
Alpha testing
Hour number
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
1
2
3
4
5
6
7
8
9

© UCLES 2015 9608/41/PRE/O/N/15


7

TASK 3

Data about books are stored in a random file of records.

• 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.

FUNCTION Hash(ISBN : STRING) RETURNS INTEGER


Address ← LeftToInt(ISBN, 3)
RETURN Address Key focus: Random files
ENDFUNCTION

The Hash function assumes the existence of the function LeftToInt, defined below:

LeftToInt(ThisString : STRING, n: INTEGER) RETURNS INTEGER


returns an integer calculated from the n-digit string, starting from the left of the string ThisString.

An error is returned if:


- any of the first n characters of ThisString are non-digit characters
- the length of ThisString is less than n

For example: LeftToInt("1575697620", 3) returns the integer 157

Note: Random files are also known as direct access files.

TASK 3.1
Write program code to implement the functions LeftToInt and Hash.

© UCLES 2015 9608/41/PRE/O/N/15 [Turn over


8

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

DECLARE DummyRecord : BookRecord

DummyRecord.ISBN ← "0000000000"

OPENFILE "BookFile" FOR WRITE // create the file by sequentially


// writing dummy records to the new file
// prior to use as a random file
FOR Count ← 1 TO 1000
PUTRECORD "BookFile", DummyRecord
ENDFOR
CLOSEFILE "BookFile"

TASK 3.3
Write program code to implement the following pseudocode to input 5 book records:

010 DECLARE NewBook : BookRecord


020
030 OPENFILE "BookFile" FOR RANDOM
040 FOR Count ← 1 TO 5
050 INPUT NewBook.ISBN
060 INPUT NewBook.Title
070 NewAddress ← Hash(NewBook.ISBN)
080 SEEK "BookFile", NewAddress
090 PUTRECORD "BookFile", NewBook
100 ENDFOR
110 CLOSEFILE "BookFile"

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

If a program tries to open a non-existent file, a run-time error will occur.

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 pseudocode for the following structured English algorithm:

Repeat until useable address found, or file is full:


If there is a record with a non-zero ISBN at the address hashed
Go to the next record address
If the end of the file is reached, start at the beginning of the file
If the hashed address is reached again, the file is full

Write program code for your algorithm and test it.

Suggested extension task


Write program code to extend your program from Task 3.5 so your program will successfully add and
delete book records, even if their ISBNs cause collisions.

© UCLES 2015 9608/41/PRE/O/N/15


Cambridge International Examinations
Cambridge International Advanced Level
* 5 9 8 6 1 5 0 5 1 8 *

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills October/November 2015
2 hours
Candidates answer on the Question Paper.
No Additional Materials are required.
No calculators allowed.

READ THESE INSTRUCTIONS FIRST

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.

Answer all questions.


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.

The maximum number of marks is 75.

This document consists of 16 printed pages.

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.

Programming language ...........................................................................................................................

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

(i) Complete the PERT chart. [7]

(ii) State the critical path.

.......................................................................................................................................[2]

(iii) Calculate the minimum number of weeks for the completion of this solution.

.......................................................................................................................................[1]

© UCLES 2015 9608/41/O/N/15


3

(b) For activity J:

(i) State the earliest start time.

Week number ................................................................................................................[1]

(ii) State the latest start time.

Week number ................................................................................................................[1]

(c) Give a reason why the project manager used a PERT chart.

...................................................................................................................................................

...............................................................................................................................................[1]

© UCLES 2015 9608/41/O/N/15 [Turn over


4

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).

These clauses have the following meaning:

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

(a) More facts are to be included.

Philippe and Gina are the parents of Meena.

Write the additional clauses to record this.

15 ..........................................................................................................................................

16 ......................................................................................................................................[2]

(b) Using the variable P, the goal

parent(P, raul)

returns

P = ali, meena

Write the result returned by the goal

parent(ali, C)

C = ......................................................................................................................................[2]

© UCLES 2015 9608/41/O/N/15


5

(c) Use the variable F to write the goal to find the father of Ahmed.

...............................................................................................................................................[1]

(d) Write the rule to show that X is the mother of Y.

mother(X, Y)

IF .............................................................................................................................................

.............................................................................................................................................. [2]

(e) W is a grandparent of Z if W is a parent of one of Z’s parents.


Complete the following rule:

grandparent(W, Z)

IF .............................................................................................................................................

...................................................................................................................................................

...............................................................................................................................................[2]

(f) Complete the rule to show that G is a grandfather of K.

grandfather(G, K)

IF .............................................................................................................................................

...................................................................................................................................................

...............................................................................................................................................[2]

© UCLES 2015 9608/41/O/N/15 [Turn over


6

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

Author: STRING ......................................................................

...................................................................... ......................................................................

...................................................................... ......................................................................

...................................................................... ......................................................................

Constructor() ......................................................................

ShowAuthor() ......................................................................

...................................................................... ......................................................................

...................................................................... ......................................................................

[7]

© UCLES 2015 9608/41/O/N/15


7

(b) Write program code

(i) for the class definition for the superclass StockItem.

Programming language .....................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.......................................................................................................................................[3]

(ii) for the class definition for the subclass Book.

Programming language .....................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.......................................................................................................................................[3]

© UCLES 2015 9608/41/O/N/15 [Turn over


8

(iii) to create a new instance of Book with:


• identifier NewBook
• title “Computers”
• author A.Nyone
• ISBN 099111
• acquired on 12/11/2001
• not out on loan

Programming language .....................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.......................................................................................................................................[3]

© UCLES 2015 9608/41/O/N/15


10

4 A binary tree Abstract Data Type (ADT) has these associated operations:

• create the tree (CreateTree)


• add an item to tree (Add)
• output items in ascending order (TraverseTree)

(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]

© UCLES 2015 9608/41/O/N/15


11

(b) The binary tree ADT is to be implemented as an array of nodes. Each node consists of data
and two pointers.

Using pseudocode, a record type, Node, is declared as follows:

TYPE Node
DECLARE Name : STRING
DECLARE LeftPointer : INTEGER
DECLARE RightPointer : INTEGER
ENDTYPE

The statement

DECLARE Tree : ARRAY[1:10] OF Node

reserves space for 10 nodes in array Tree.

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]

© UCLES 2015 9608/41/O/N/15 [Turn over


12

(c) A programmer needs an algorithm for outputting items in ascending order. To design this, the
programmer writes a recursive procedure in pseudocode.

(i) Complete the pseudocode:

01 PROCEDURE TraverseTree(BYVALUE Root: INTEGER)

02 IF Tree[Root].LeftPointer .................................................................

03 THEN

04 TraverseTree( .............................................................................)

05 ENDIF

06 OUTPUT .............................................................................................. .Name

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.

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

Line number ..................................................................................................................[2]

(iii) Write the pseudocode call required to output all names stored in Tree.

...........................................................................................................................................

.......................................................................................................................................[1]

© UCLES 2015 9608/41/O/N/15


13

Question 5 begins on page 14.

© UCLES 2015 9608/41/O/N/15 [Turn over


14

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.

FUNCTION Hash(MemberID : INTEGER) RETURNS INTEGER

Address ← MemberID MOD 100

RETURN Address

ENDFUNCTION

(a) New members with the following member IDs have joined the sports club:

1001, 3005, 4096, 2098, 7002

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]

© UCLES 2015 9608/41/O/N/15


15

(b) (i) The program stores a new member’s data in the record variable NewMember. The field
MemberID stores the member ID.

Complete the pseudocode:

10 // generate record address

20 NewAddress ← ..........................................................................................................

30 // move pointer to the disk address for the record

40 SEEK ...........................................................................................................................

50 PUTRECORD "MembershipFile", ..........................................................................


[4]

(ii) Before records can be saved to the file MembershipFile, the file needs to be opened.

Complete the pseudocode.

01 TRY

02 OPENFILE ..................................................................................... FOR RANDOM

03 EXCEPT

04 ..............................................................................................................................

05 ENDTRY
[2]

(iii) A record with member ID 9001 is to be stored.

Explain the problem that occurs when this record is saved.

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.......................................................................................................................................[2]

(iv) Describe a method, without changing the function Hash, to handle the problem identified
in part (b)(iii).

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.......................................................................................................................................[2]

© UCLES 2015 9608/41/O/N/15 [Turn over


16

(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.

© UCLES 2015 9608/41/O/N/15


Page 2 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2015 9608 41

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]

(iii) 43 weeks [1]

(b) (i) week number 25 [1]

(ii) week number 32 [1]

(c) To see what activities can be done in parallel // show dependencies


To record changes to project timings [max. 1]

© Cambridge International Examinations 2015


Page 3 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2015 9608 41

2 (a) parent(philippe, meena).


parent(gina, meena). [2]

(b) ahmed, aisha, raul [2]

(c) father(F, ahmed). [1]

(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]

© Cambridge International Examinations 2015


Page 4 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2015 9608 41

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]

© Cambridge International Examinations 2015


Page 5 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2015 9608 41

(b) (i) Mark as follows:


Class header
Methods
Properties

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]

© Cambridge International Examinations 2015


Page 6 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2015 9608 41

(ii) Mark as follows:


Class header and showing superclass
Methods
Properties

Pascal

TYPE Book = CLASS (StockItem)


PUBLIC
Procedure ShowAuthor();
Procedure ShowISBN();
PRIVATE
Author : STRING;
ISBN : STRING;
END;

Python

class Book(StockItem) :
def __init__(self) :
self.__Author = ""
self.__ISBN = ""
def ShowAuthor() :
pass
def ShowISBN() :
pass

VB.NET

Class Book : Inherits StockItem


Public Sub ShowAuthor()
End Sub
Public Sub ShowISBN()
End Sub
Private Author As String
Private ISBN As String ‘ reject integer
End Class [3]

© Cambridge International Examinations 2015


Page 7 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2015 9608 41

(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

Dim NewBook As Book = New Book() 1


NewBook.Title = "Computers"
NewBook.Author = "A.Nyone"
NewBook.ISBN = "099111" 1
NewBook.DateAcquired = #12/11/2001#
NewBook.OnLoan = False 1 [3]

© Cambridge International Examinations 2015


Page 8 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2015 9608 41

4 (a)

[4]

(b)
Tree

RootPointer Name LeftPointer RightPointer


1 [1] Dodi 5 2

[2] Farai 3 4

FreePointer [3] Elli 0 0


8 [4] George 0 0

[5] Ben 7 6

[6] Celine 0 0

[7] Ali 0 0

[8] 9 0

[9] 10 0

[10] 0 0
[7]

© Cambridge International Examinations 2015


Page 9 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2015 9608 41

(c) (i) 01 PROCEDURE TraverseTree(BYVALUE Root : INTEGER)


02 IF Tree[Root].LeftPointer < > 0
03 THEN
04 TraverseTree(Tree[Root].LeftPointer)
05 ENDIF
06 OUTPUT Tree[Root].Name
07 IF Tree[Root].RightPointer < > 0
08 THEN
09 TraverseTree(Tree[Root].RightPointer)
10 ENDIF
11 ENDPROCEDURE [5]

(ii) A procedure that calls itself // is defined in terms of itself


Line number: 04/09 [2]

(iii) TraverseTree(RootPointer) [1]

5 (a)
MembershipFile

Address MemberID other member data

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

1001 and 7002 and 3005 1


4096 and 2098 1 [2]

© Cambridge International Examinations 2015


Page 10 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2015 9608 41

(b) (i) 10 // generate record address


20 NewAddress  Hash(NewMember.MemberID)
30 // move pointer to the disk address for the record
40 SEEK NewAddress
50 PUTRECORD "MembershipFile", NewMember [4]

(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]

(iv) Create an overflow area


The ‘home’ record has a pointer to others with the same key
OR
Store the overflow record at the next available address
in sequence
OR
Re-design the hash function ….
to generate a wider range of indexes // to create fewer collisions [2]

(v) 41 GETRECORD "MembershipFile", CurrentRecord


42 WHILE CurrentRecord.MemberID <> 0
43 NewAddress  NewAdress + 1
44 IF NewAddress > 99 THEN NewAddress  0
45 SEEK NewAddress
46 GETRECORD "MembershipFile", CurrentRecord
47 ENDWHILE [max. 4]

© Cambridge International Examinations 2015


Cambridge International Examinations
Cambridge International Advanced Level

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills May/June 2016
PRE-RELEASE MATERIAL
* 3 2 9 1 7 5 7 6 8 9 *

No Additional Materials are required.


This material should be given to the relevant teachers and candidates as soon as it has been received
at the Centre.

READ THESE INSTRUCTIONS FIRST

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.

This document consists of 10 printed pages and 2 blank pages.

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.

Questions on the examination paper may ask the candidate to write:


• structured English
• pseudocode
• program code

A program flowchart should be considered as an alternative to pseudocode for the documenting of an


algorithm design.

Candidates should be confident with:


• the presentation of an algorithm using either a program flowchart or pseudocode
• the production of a program flowchart from given pseudocode (or the reverse)

Declaration of variables

The syllabus document shows the syntax expected for a declaration statement in pseudocode.

DECLARE <identifier> : <data type>

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:

(i) Write program code for the new design.

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.

Programming language ...................................................................................................

..........................................................................................................................................

..........................................................................................................................................

© UCLES 2016 9608/41/PRE/M/J/16


3

Structured English – Variables

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.

© UCLES 2016 9608/41/PRE/M/J/16 [Turn over


4

Jackson Structured Programming (JSP)


Key focus: JSP data
structure diagrams

A JSP data structure diagram is used to represent the data used by a problem.

The tasks that follow introduce you to the symbols used.

Task 1

1.1 This symbol is used in a JSP data structure diagram. What is it used to represent?

• a data item or data component


• a subroutine
• a procedure
• a function

1.2 Which one statement correctly describes this diagram?

A B C

• It shows a sequence of data items which can be presented in any order.


• It shows alternative data items.
• It shows a sequence of data items structured in the order A, then B, then C.

1.3 Which are the three true statements for the JSP data structure diagram shown below?

A B C

1 Data structure X is made up of items A, then B, then C.


2 Data structure X is made up of a combination of items A, B and C.
3 The JSP data structure diagram illustrates sequence.
4 The JSP data structure diagram shows stepwise refinement.

1.4 A customer transaction, CustomerTransaction, consists of:


• a customer number, CustomerNumber
• a product code, ProductCode
• the quantity, Quantity

in this given order.


Key focus:
Using ‘sequence’ …
Draw the JSP data structure diagram.

© UCLES 2016 9608/41/PRE/M/J/16


5

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.

Draw the JSP data structure diagram.

Task 3 Key focus:


Using ‘sequence’ …
An employee record Record consists of:

• the employee name EmployeeName


• the address EmployeeAddress
• a pay code EmployeePayCode, which is either Full, Part Casual

in this given order.

Draw the JSP data structure diagram.

Task 4

4.1 This symbol is used in a JSP data structure diagram. What is it used to represent?

• a process, action or operation on a data item


*
• iteration of data item
• selection of a data item
• a procedure

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.

Draw the JSP data structure diagram.

© UCLES 2016 9608/41/PRE/M/J/16 [Turn over


6

Task 5

A shipping company has a number of merchant ships. Data are recorded for all the voyages made by
each ship.

The data are stored in a file ShipFile. The file has:

• 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

FileHeader FileBody FileTrailer 2

*
Ship 3

*
ShipName ShipVoyage 4

To build up the JSP data structure diagram:

1 the file has the name ShipFile.

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.

© UCLES 2016 9608/41/PRE/M/J/16


7

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

FileHeader FileBody FileTrailer

*
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.

This was hinted at in Task 4.3.

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.

Draw the JSP data structure diagram.

© UCLES 2016 9608/41/PRE/M/J/16 [Turn over


8

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.

The following is a list with a sequence of elements.

[budapest,paris,london,singapore,dhaka,oslo,brussels,amsterdam,cairo]

[] denotes an empty list.

A variable can be used to represent a list.

Cities represents [budapest,paris,london,singapore,dhaka,oslo,


brussels,amsterdam,cairo]

The operator | is used with a list.


Key focus:
For example, [X|Y] denotes a list with: The ‘⎜’ list operator

X a variable representing the first list element, the head


Y a variable consisting of the remaining list elements, the tail

Example:

If Cities represents [X|Y]

• 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.

isEmpty(X) returns: Key focus:


Predicates with lists
TRUE when X = []
FALSE when X has one or more elements

Example:

isEmpty(Cities) would return FALSE.

© UCLES 2016 9608/41/PRE/M/J/16


9

7.1

The list [gibraltar,hanoi] is denoted as [A|B]

State the values of A and B.

A = ......................................................................................

B = ......................................................................................

7.2

The following two lists are identical:

[kingston,rome,riga|C] = [kingston,rome,riga,bangkok,minsk]

State the value of C.

C = ......................................................................................

7.3

The following two lists are identical:

[suva,stanley] = [D,E|F]

State the value of F.

F = ......................................................................................

Consider this second predicate:

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?

......................................................................................

© UCLES 2016 9608/41/PRE/M/J/16 [Turn over


10

7.4.2

removeAndCompare([orange,banana],[ ],[orange,banana])

What is returned by this predicate?

......................................................................................

© UCLES 2016 9608/41/PRE/M/J/16


Cambridge International Examinations
Cambridge International Advanced Level
* 9 7 8 8 0 0 7 3 6 1 *

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills May/June 2015
2 hours
Candidates answer on the Question Paper.
No Additional Materials are required.
No calculators allowed.

READ THESE INSTRUCTIONS FIRST

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.

Answer all questions.


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.

The maximum number of marks is 75.

This document consists of 16 printed pages.

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.

Programming language ...........................................................................................................................

© UCLES 2015 9608/41/M/J/15


3

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.

Current state Event Next state


Locked Insert coin Unlocked
Locked Push Locked
Unlocked Attempt to insert coin Unlocked
Unlocked Pass through Locked

Complete the state transition diagram for the turnstile:

..............................

.............................. ..............................

.............................. ..............................

start ..............................

[5]

© UCLES 2015 9608/41/M/J/15 [Turn over


4

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).

These clauses have the following meaning:

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

(a) More facts are to be included.

The travel writer visited the city of Santiago which is the capital city of Chile, in the continent
of South America.

Write additional clauses to record this.

17 ............................................................................................................................................

...................................................................................................................................................

18 ............................................................................................................................................

...................................................................................................................................................

19 ............................................................................................................................................

...................................................................................................................................................

20 ............................................................................................................................................

.............................................................................................................................................. [4]

© UCLES 2015 9608/41/M/J/15


5

(b) Using the variable ThisCountry, the goal

country_in_continent(ThisCountry, europe)

returns

ThisCountry = belgium, uk

Write the result returned by the goal:

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]

© UCLES 2015 9608/41/M/J/15 [Turn over


6

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

(a) Complete the decision table.

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

have discount card Y N Y N Y N Y N

No discount
Actions

5% discount

10% discount

[4]

(b) Simplify your solution by removing redundancies.

goods totalling
more than $20
Conditions

goods totalling
more than $100

have discount card

No discount
Actions

5% discount

10% discount

[5]

© UCLES 2015 9608/41/M/J/15


7

(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.

Identifier Data type


GoodsTotal INTEGER
HasDiscountCard BOOLEAN

Write program code for this function.

Programming language .............................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

.............................................................................................................................................. [6]

© UCLES 2015 9608/41/M/J/15 [Turn over


8

4 A payroll program is to be written using an object-oriented programming language. An Employee


class is designed. Two subclasses have been identified:
• HourlyPaidEmployee who is paid a monthly wage calculated from their hourly rate of pay
and the number of hours worked during the month
• SalariedEmployee who is paid a monthly wage which is one 12th of their annual salary

(a) Draw an inheritance diagram for these classes.

[3]

(b) The design for the Employee class consists of:


• properties
• EmployeeName
• EmployeeID
• AmountPaidThisMonth

• methods
• SetEmployeeName
• SetEmployeeID
• CalculatePay

Write program code for the class definition of the superclass Employee.

Programming language .............................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

.............................................................................................................................................. [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]

© UCLES 2015 9608/41/M/J/15 [Turn over


10

5 Data is stored in the array NameList[1:10]. This data is to be sorted.

(a) (i) Complete the pseudocode algorithm for an insertion sort.

FOR ThisPointer ← 2 TO .................................................


// use a temporary variable to store item which is to
// be inserted into its correct location
Temp ← NameList[ThisPointer]
Pointer ← ThisPointer – 1

WHILE (NameList[Pointer] > Temp) AND .................................................


// move list item to next location
NameList[....................................] ← NameList[....................................]
Pointer ← .................................................
ENDWHILE

// insert value of Temp in correct location


NameList[....................................] ← .................................................
ENDFOR
[7]

(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]

© UCLES 2015 9608/41/M/J/15


11

(b) An alternative sort algorithm is a bubble sort:

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]

© UCLES 2015 9608/41/M/J/15 [Turn over


12

(ii) Rewrite the algorithm in part (b), using pseudocode, to reduce the number of
unnecessary comparisons. Use the same variable names where appropriate.

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

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

© UCLES 2015 9608/41/M/J/15


13

6 A queue Abstract Data Type (ADT) has these associated operations:

• create queue
• add item to queue
• remove item from queue

The queue ADT is to be implemented as a linked list of nodes.

Each node consists of data and a pointer to the next node.

(a) The following operations are carried out:

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]

© UCLES 2015 9608/41/M/J/15 [Turn over


14

(b) Using pseudocode, a record type, Node, is declared as follows:

TYPE Node
DECLARE Name : STRING
DECLARE Pointer : INTEGER
ENDTYPE

The statement

DECLARE Queue : ARRAY[1:10] OF Node

reserves space for 10 nodes in array Queue.

(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]

© UCLES 2015 9608/41/M/J/15


15

(ii) The algorithm for adding a name to the queue is written, using pseudocode, as a
procedure with the header:

PROCEDURE AddName(NewName)

where NewName is the new name to be added to the queue.

The procedure uses the variables as shown in the identifier table.

Identifier Data type Description


Queue Array[1:10] OF Node Array to store node data
NewName STRING Name to be added
FreePointer INTEGER Pointer to next free node in array
HeadPointer INTEGER Pointer to first node in queue
TailPointer INTEGER Pointer to last node in queue
CurrentPointer INTEGER Pointer to current node

PROCEDURE AddName(BYVALUE NewName : STRING)


// Report error if no free nodes remaining
IF FreePointer = 0
THEN
Report Error
ELSE
// new name placed in node at head of free list
CurrentPointer ← FreePointer
Queue[CurrentPointer].Name ← NewName
// adjust free pointer
FreePointer ← Queue[CurrentPointer].Pointer
// if first name in queue then adjust head pointer
IF HeadPointer = 0
THEN
HeadPointer ← CurrentPointer
ENDIF
// current node is new end of queue
Queue[CurrentPointer].Pointer ← 0
TailPointer ← CurrentPointer
ENDIF
ENDPROCEDURE

© UCLES 2015 9608/41/M/J/15 [Turn over


16

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.

© UCLES 2015 9608/41/M/J/15


Pag
P ge 2 Mar
M k Sch
S hemmee Sylllab
bus Pape
P er
C mb
Cam brid
dge
e In
nte
ern
natiion
nal A Le
eve
el – May
M y/J
Jun
ne 2016
6 9 08
960 4
41

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

Question Answer Marks

(ii) Accept () instead of [] 6


01 Current ← StartPtr
02 IF Current = 0
03 THEN
OUTPUT "Empty List" (or similar message)
04
(accept without quotes) Reject “Error”
05 ELSE
06 IsFound ← FALSE
07 INPUT ThisSurname
08 REPEAT
09 IF SurnameList[Current].Surname = ThisSurname
10 THEN
11 IsFound ← TRUE
12 OUTPUT "Surname found at position ", Current
13 ELSE
14 // move to the next list item
15 Current ← SurnameList[Current].Ptr
16 ENDIF
17 UNTIL IsFound = TRUE OR Current = 0
18 IF IsFound = FALSE
19 THEN
20 OUTPUT "Not Found"
21 ENDIF
22 ENDIF

Accept = for assignment

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

© Cambridge International Examinations 2016


Page 4 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2016 9608 41

Question Answer Marks

(b) (i) MyList 4


Index Item 1 2 3 4 5 6 7 8 9 10

1 9 3 5 8 9 13 16 27 0 0 0

13
4

5 16

6 27

7 0

Note: Final mark only if no additional entries in table


Accept last row to show all final values

(ii) Any one from: 1


Deletes/removes parameter value/ Item (from the array MyList)
// Deletes the first entry (in MyList) that equals or is bigger than Item

Overwrites Item by moving subsequent items up/down/across/left R right

© Cambridge International Examinations 2016


Page 5 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2016 9608 41

Question Answer Marks

3 (a) 7
HIRE-TRANS

F_BODY F_TRAILER

TRANS

Customer
data Hire data

Customer Hire start Number of


CustomerID Car Reg
Name date days hired

Mark as follows:
Label F_TRAILER 1
Label TRANS 1

Customer box (Accept label Customer) 1


Hire box (Accept label Hire) 1

Customer fields : Customer Name, CustomerID/IDnumber 1


Hire fields: Car Reg 1
Hire fields: Hire start date, Number of days hired 1

accept level 5 fields in any order


Ignore parent

© Cambridge International Examinations 2016


Page 6 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2016 9608 41

Question Answer Marks

(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

* For CAR_HIRE label:


Accept: Hires / hired / Car data / hire data / hire record / one or more hires

© Cambridge International Examinations 2016


Page 7 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2016 9608 41

Question Answer Marks

4 (a) (i) a03, h07, a23 1


accept in any order, must be lower case

(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.

(c) (i) a07 2


[p03]

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

5 (a) (i) Mark Description Expected result (Grade) 3

Normal FAIL/PASS/MERIT/DISTINCTION
Abnormal Error
Extreme/Boundary FAIL/PASS/MERIT/DISTINCTION

3 × (mark + matching grade)


for abnormal data accept negative values, non-integer values, Expected Result: Error
0 and marks above 100 are still acceptable values
Do not accept FAIL in expected result column for Abnormal data

(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

© Cambridge International Examinations 2016


Page 8 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2016 9608 41

Question Answer Marks

(c) 1 Open a non-existent file Max 3


2 Directory path does not exist
3 Attempt to read past the end of the file // attempt to read an empty file
4 Array subscript is out of range
5 Non-integer value / corrupt data read
6 File already open in a different mode // wrong file permissions

(d) (i) 09 // 9 1

(ii) 1 Line 11 catches exceptions (only) between lines 05 and 10 1 Max 3


2 Line 11 stops the program from crashing 1
3 Different exception types recognised 1
4 Each exception type has an appropriate message output 1
5 The program language has an (object) type EXCEPTION 1
6 ThisException is the instance of EXCEPTION which has been raised 1
7 EXCEPTION objects have a ‘Message’ property
// the message property for ThisException is
“Arithmetic operation resulted in an overflow” 1

6 (a) 4

Max 3 marks if extra states/transitions added.

© Cambridge International Examinations 2016


Page 9 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2016 9608 41

Question Answer Marks

(b) (i) Mark as follows: 4


1 Declaration for array (character or string data type)
2 FOR loop for x going from 1 to 8, generating column index used in array
3 FOR loop for y going from 1–2, 3–6, 7–8
(Accept all squares being set to 'E' and then overwritten with 'B', 'W'
respectively)
4 Setting squares to 'B', 'E', 'W' (must be in quotes, accept single or double)

(ii) Mark as follows: Max 5


1 Procedure heading and declaration of 2 local variables 1
2 Establishing the stopper colour – opposite to the mover 1
3 Test for piece in column 1 (x>1) // column 8 (x<8) 1
4 Test for ‘E’ 1
5 Correct method for moving left // for moving right 1
6 until edge of board reached 1
7 until other colour (stopper colour) encountered 1
8 until own colour encountered (PieceColour) 1
9 Correct output for cell indexes 1
(accept for moving in 1 direction only)
10 including the ‘REMOVE’ message 1

Note: must use given parameter identifiers: PieceColour, xCurrent, yCurrent

(c) (i) Classes could be designed for : Max 2


• the board
• a piece
Containment (Board contains Pieces)
The pieces are instances/objects (of the Piece class)

© Cambridge International Examinations 2016


Page 10 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2016 9608 41

Question Answer Marks

(ii) Accept any reasonable answer, for example: Max 2

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

Accept other classes: Game, Player

© Cambridge International Examinations 2016


Page 11 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2016 9608 41

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.

© Cambridge International Examinations 2016


Page 12 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2016 9608 41

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"

Alternative declarations of Board array :

Board = [[""] * 9 for i in range(9)]

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 = [["E"] * 9 for i in range(9)] // Board =[["E"]*9]*9


for Row in range(1, 3) :
for Column in range(1, 9) :
Board[Row][Column] = "B"
for Row in range(7, 9) :
for Column in range(1, 9) :
Board[Row][Column] = "W"

Board =[]
for i in range(9):
Board.append(["E"]*9)

© Cambridge International Examinations 2016


Page 13 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2016 9608 41

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

© Cambridge International Examinations 2016


Page 14 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2016 9608 41

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;

© Cambridge International Examinations 2016


Page 15 Mark Scheme Syllabus Paper
Cambridge International A Level – May/June 2016 9608 41

PYTHON

def ValidMoves(PieceColour, xCurrent, yCurrent) :


if PieceColour == "B" :
StopperColour = "W"
else :
StopperColour = "B"
print("Possible moves are : ")
if xCurrent != 1 :
print("Moving LEFT . . .")
i = xCurrent – 1
NoFurther = False
while i > 0 and NoFurther == False :
if Board[i][yCurrent] == "E" :
print(str(i) + " " + str(yCurrent))
if Board[i][yCurrent] == StopperColour :
print(str(i) + " " + str(yCurrent) + " REMOVE PIECE")
NoFurther = True
i = i – 1
if xCurrent != 8 :
print("Moving RIGHT . . .")
i = xCurrent + 1
NoFurther = False
while i < 9 and NoFurther == False :
if Board[i][yCurrent] == "E" :
print(str(i) + " " + str(yCurrent))
if Board[i][yCurrent] == StopperColour :
print(str(i) + " " + str(yCurrent) + " REMOVE PIECE")
NoFurther = True
i = i + 1

© Cambridge International Examinations 2016


Cambridge International Examinations
Cambridge International Advanced Level

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills October/November 2016
PRE-RELEASE MATERIAL
This material should be given to the relevant teachers and candidates as soon as it has been received
* 2 8 5 7 7 9 6 9 5 0 *

at the Centre.

READ THESE INSTRUCTIONS FIRST

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.

This document consists of 12 printed pages.

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.

Questions on the examination paper may ask the candidate to write:


• structured English
• pseudocode
• program code

A program flowchart should be considered as an alternative to pseudocode for the documenting of an


algorithm design.

Candidates should be confident with:


• the presentation of an algorithm using either a program flowchart or pseudocode
• the production of a program flowchart from given pseudocode (or the reverse)

Declaration of variables

The syllabus document shows the syntax expected for a declaration statement in pseudocode.

DECLARE <identifier> : <data type>

If Python is the chosen language, each variable’s identifier (name) and its intended data type must be
documented using a comment statement.

Structured English – Variables

An algorithm in pseudocode uses variables, which should be declared. An algorithm in structured


English does not always use variables. In this case, the candidate needs to use the information given
in the question to complete an identifier table. The table needs to contain an identifier, data type and
description for each variable.

© UCLES 2016 9608/41/PRE/O/N/16


3

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

Syllabus section 2.4.1 refers to an Integrated Development Environment (IDE).


Syllabus section 4.3.4 refers to the use of development tools and 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

Write program code for the following insertion sort algorithm.


Correct any syntax errors.
Then use the debugger to find other types of error.

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.

PROCEDURE Sort(BYREF Names : ARRAY OF STRING, BYVAL Start : INTEGER,


BYVAL Finish : INTEGER)
FOR ThisPointer ←
Start + 1 TO Finish
ThisName ←
Names[ThisPointer]
Pointer ←
ThisPointer – 1
WHILE Names[Pointer] > ThisValue OR Pointer > 0
Names[Pointer + 1] ←
Names[Pointer]
Pointer ←
Pointer – 1
ENDWHILE
Names[Pointer + 1] ←
ThisName
ENDFOR
ENDPROCEDURE

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?

© UCLES 2016 9608/41/PRE/O/N/16 [Turn over


4

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

© UCLES 2016 9608/41/PRE/O/N/16


5

Notes:

# denotes immediate addressing


B denotes a binary number, for example B01001010
& denotes a hexadecimal number, for example &4A

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

Key focus: Low-level Programming

Write assembly language program code using the instruction set provided on page 4.

Tasks 2.1 to 2.5 show a high-level language construct written in pseudocode.


Each of these tasks consists of writing the assembly language.

© UCLES 2016 9608/41/PRE/O/N/16 [Turn over


6

TASK 2.1

X ← A + B
END

Instruction
Label Op Comment
Operand
code
START: // load the content of A into ACC

// add the content of B to content of ACC

// store content of ACC at address X

END // end of program

X:

A: 5

B: 3

© UCLES 2016 9608/41/PRE/O/N/16


7

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

// compare the content of ACC with content of A

// if not equal (FALSE), jump to ELSE

THEN: // instruction for THEN part start here

JMP ENDIF // jump over the ELSE part

ELSE: // instructions for ELSE part start here

ENDIF: // remainder of program continues from here

END // end of program

A: 65

X: 67

Note: the built-in function CHR(X) returns the character that is represented by the ASCII code held in X.

© UCLES 2016 9608/41/PRE/O/N/16 [Turn over


8

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

// is content of ACC = content of A ?

// if not equal (FALSE), jump to LOOP

END // end of program

X: 90

A: 65

© UCLES 2016 9608/41/PRE/O/N/16


9

TASK 2.4

FOR COUNT ←
1 TO 4
OUTPUT CHARS[COUNT]
ENDFOR
END

Instruction
Label Op Comment
Operand
code
// set ACC to zero

// store content of ACC in COUNT

LOOP: // increment COUNT starts here

// instructions to be repeated start here

// COUNT = 4 ?

// if not equal (FALSE), jump to LOOP

END // end of program

COUNT:

CHARS: 72 // 'H'

69 // 'E'

76 // 'L'

80 // 'P'

© UCLES 2016 9608/41/PRE/O/N/16 [Turn over


10

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

// jump back to start of loop

END // end of program

X: 4
B: 0
CHARS: 72 // 'H'
69 // 'E'
76 // 'L'
80 // 'P'

© UCLES 2016 9608/41/PRE/O/N/16


11

TASK 2.6

Output a string using indirect addressing.

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

// load content of address 100

// increment ACC

// store content of ACC at address 100

// is content of ACC = 107 ?

// if not equal (FALSE), jump to LOOP

END // end of program

100 102

101

102 77 // 'M'

103 65 // 'A'

104 84 // 'T'

105 72 // 'H'

106 83 // 'S'

107

© UCLES 2016 9608/41/PRE/O/N/16 [Turn over


12

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

END // end of program

X: B10101111

Y: // what does the value of Y tell you about X ?

MASK: B00000001

Write simple programs using the different bitwise operations (AND, OR, XOR) and different MASK content.

Identify the operation and MASK bit pattern to:

• set a bit to 1, leaving all other bits unchanged


• set a bit to 0, leaving all other bits unchanged
• test whether a specific bit is 1
• test whether a specific bit is 0

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.

© UCLES 2016 9608/41/PRE/O/N/16


Cambridge International Examinations
Cambridge International Advanced Level
* 8 1 1 8 3 7 8 6 0 3 *

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills October/November 2016
2 hours
Candidates answer on the Question Paper.
No Additional Materials are required.
No calculators allowed.

READ THESE INSTRUCTIONS FIRST

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.

Answer all questions.


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.

The maximum number of marks is 75.

This document consists of 16 printed pages.

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.

The operation of the safety deposit box is as follows:

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:

Current state Event Next state


Door open, no code set 4-digit code entered Door open, code set
Door open, code set R entered Door open, no code set
Door open, code set Close door Door closed
Door closed Set code entered Door locked
Door locked Set code entered Door open, code set
Door locked R entered Door locked

© UCLES 2016 9608/41/O/N/16


3

(a) Complete the state-transition diagram.

.......................................................
start

............................
Door open
no code set
............................
......................................

...............................................

...............................................

Door closed

............................

............................

...............................................
...............................................
[7]

© UCLES 2016 9608/41/O/N/16 [Turn over


4

(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

Write program code for the following methods.

Programming language ............................................................................................................

(i) Create()

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...................................................................................................................................... [3]

(ii) Reset()

...........................................................................................................................................

...........................................................................................................................................

...................................................................................................................................... [2]

© UCLES 2016 9608/41/O/N/16


5

(iii) SetState()

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...................................................................................................................................... [2]

(iv) SetNewCode()

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...................................................................................................................................... [2]

(v) The user must enter a 4-digit code.

Write program code for a function Valid(s : STRING)that returns:

• TRUE if the input string s consists of exactly 4 digits


• FALSE otherwise

Programming language .....................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...................................................................................................................................... [4]

© UCLES 2016 9608/41/O/N/16 [Turn over


6

(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

Yes Is State = Yes


Is Chars = 'R'? CALL Reset()
"Open-CodeSet"?

No No
CALL SetState("Open-NoCode")

Is Chars = Code? Yes Is State = Yes


CALL SetState("Open-CodeSet")
"Locked"?

No No

Is State = Yes
CALL SetState("Locked")
"Closed"?

No

Is Chars = "" Yes


and State = CALL SetState("Closed")
"Open-CodeSet"?

No

Yes Is State = Yes


Is Chars a valid CALL SetNewCode(Chars)
4-digit code? "Open-NoCode"?

No No
CALL SetState("Open-CodeSet")
OUTPUT "Error – OUTPUT "Error –
code format does not match
incorrect" set code"

ENDMETHOD

© UCLES 2016 9608/41/O/N/16


7

Programming language .....................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.....................................................................................................................................[12]

© UCLES 2016 9608/41/O/N/16 [Turn over


8

(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.

The main program design is:

instantiate ThisSafe (create and initialise ThisSafe)


loop forever (continually use ThisSafe)
call StateChange() method
end loop

Write program code for the main program.

Programming language .....................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...................................................................................................................................... [4]

© UCLES 2016 9608/41/O/N/16


9

(c) It is possible to declare properties and methods as either public or private.

The programmer has modified the class design for SafetyDepositBox as follows:

SafetyDepositBox
PRIVATE
Code : STRING
State : STRING
PUBLIC
Create()
StateChange()
PRIVATE
Reset()
SetState()
SetNewCode()

(i) Describe the effects of declaring the SafetyDepositBox properties as private.

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...................................................................................................................................... [2]

(ii) Describe the effects of declaring two methods of the class as public and the other three
as private.

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...................................................................................................................................... [2]

© UCLES 2016 9608/41/O/N/16 [Turn over


10

2 Circle the programming language that you have studied:

Visual Basic (console mode) Python Pascal Delphi (console mode)

(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]

© UCLES 2016 9608/41/O/N/16


12

(iii) The table shows a module definition for BinarySearch in three programming languages.

Study one of the examples. Indicate your choice by circling A, B or C:

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

© UCLES 2016 9608/41/O/N/16


13

The programming environment reported a syntax error in the BinarySearch code.

State the line number: .......................................................................................................

Write the correct code for this line.

.......................................................................................................................................[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.

State the type of error: .......................................................................................................

Write down the line number where the error occurs.

...........................................................................................................................................

Write the correct code for this line.

.......................................................................................................................................[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]

© UCLES 2016 9608/41/O/N/16 [Turn over


14

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.

© UCLES 2016 9608/41/O/N/16


15

Op
Label Operand Comment
code
START: // initialise index register to zero

// initialise COUNT to zero

LOOP1: // load character from indexed address NAME

// output character to screen

// increment index register

// increment COUNT starts here

// is COUNT = MAX ?

// if FALSE, jump to LOOP1

REVERSE: // decrement index register

// set ACC to zero

// store in COUNT

LOOP2: // load character from indexed address NAME

// output character to screen

// decrement index register

// increment COUNT starts here

// is COUNT = MAX ?

// if FALSE, jump to LOOP2

// end of program

COUNT:

MAX: 4

NAME: B01000110 // ASCII code in binary for 'F'

B01010010 // ASCII code in binary for 'R'

B01000101 // ASCII code in binary for 'E'

B01000100 // ASCII code in binary for 'D'

[15]
© UCLES 2016 9608/41/O/N/16 [Turn over
16

4 Commercial software usually undergoes acceptance testing and integration testing.

Distinguish between the two types of testing by stating:

• who does the testing


• when the testing occurs
• the specific purpose of each type of testing

(i) Acceptance testing

Who ..........................................................................................................................................

...................................................................................................................................................

When ........................................................................................................................................

...................................................................................................................................................

Purpose ....................................................................................................................................

...............................................................................................................................................[3]

(ii) Integration testing

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.

© UCLES 2016 9608/41/O/N/16


Page 2 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2016 9608 41

1 (a) 1 mark for both Set code entered correct. 1 mark for each label. [7]

(b) (i) 1 mark per bullet to max 3 [3]


• Method header
• initialising Code to ""
• initialising State to "Open-NoCode"
e.g.

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

(ii) 1 mark per bullet to max 2 [2]


• method header
• Setting code to ""
e.g.

PYTHON:
def reset(self):
self.__code = ""

PASCAL/DELPHI:
procedure SafetyDepositBox.Reset();
begin
Code := '';
end;

VB:
Public Sub Reset()
Code = ""
End Sub

(iii) 1 mark per bullet to max 2 [2]


• method header with parameter
• setting state to parameter value
• Outputting state
e.g.

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

(iv) 1 mark per bullet to max 2 [2]


• setting code to parameter
• Outputting New cost set and code
e.g.

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

(v) 1 mark per bullet to max 4 [4]


• function header taking string parameter, returns Boolean
• check length of string is 4
• check each character is a digit
• return of correct Boolean value for both cases
e.g

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;

VB: ByVal optional


Public Function valid(ByVal s As String) As Boolean
If s Like "####" Then
Return True
Else
Return False
End If
End Function

© UCLES 2016
Page 6 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2016 9608 41

(vi) 1 mark per bullet to max 12 [12]


• read Chars from keyboard
• check if ‘R’ and state = Open-CodeSet
• call method Reset() & method SetState
• if Chars is the set code:
• check if locked
• set state to Open-CodeSet
• else if closed
• then set state to Locked
• if Chars is empty and State is “Open-CodeSet” then setState to closed
• if Chars is a valid 4-digit code and state is Open-NoCode
• call setNewCode and SetState
• outputting correct error messages for not valid 4-digit and state is not Open-NoCode
e.g.

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

(vii) 1 mark per bullet to max 4 [4]


• method header
• Initialising ThisSafe to instance of SafetyDepositBox
• Loop forever
• Call method StateChange on ThisSafe
e.g.

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

(c) (i) 1 mark per bullet to max 2: [2]


• The attributes can only be accessed in the class
• Properties are needed to get/set the data // It provides/uses encapsulation
• Increase security/integrity of attributes

(ii) 1 mark per bullet [2]


• The public methods can be called anywhere in the main program // Public methods
can be inherited by sub-classes
• The private methods can only be called within the class definition // cannot be called
outside the class definition // Private methods cannot be inherited by sub-classes

2 (a) (i) 1 mark per feature to max 3 [3]


e.g.
• auto-indent
• auto-complete / by example
• colour-coded keywords/ strings/ comments/ built-in functions/ user-defined function
names
• pop-up help
• can set indent width
• expand/collapse subroutines/code
• block highlighting
incorrect syntax highlighting/underlining //dynamic syntax checker

(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

Line 3 Line 5 Line 4 [1]

while (Index == -1) WHILE (Index = -1) DO WHILE (Index = -


& (Low <= High): AND (Low <= High) 1) AND (Low <= [1]
DO High)

© UCLES 2016
Page 10 Mark Scheme Syllabus Paper
Cambridge International A Level – October/November 2016 9608 41

(b) (i) Python: compiled/interpreted [1]


VB.NET: compiled
Pascal: compiled/interpreted
Delphi: compiled/interpreted

(ii)
Logic error Logic error Logic error [1]

11 return(Index) 14 Result := Index; 14 BinarySearch = Index [1]

(iii) 1 mark for each name, 1 for each description [4]

• breakpoint
• a point where the program can be halted to see if the program works at this point

• stepping / step through


• executes one statement at a time and then pauses to see the effect of each
statement

• variable watch window


• observe how variables changed during execution

© 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]

OUT // output character to screen [1]


INC IX // increment index register [1]
LDD COUNT // increment COUNT starts here
INC ACC [1]
STO COUNT
CMP MAX // is COUNT = MAX? [1]
JPN LOOP1 // if FALSE, jump to LOOP1 [1]
REVERSE: DEC IX // decrement index register [1]
LDM #0 // set ACC to zero
[1]
STO COUNT // store in COUNT
// load character from indexed address
LOOP2: LDX NAME
NAME [1]
OUT // output character to screen
DEC IX // decrement index register [1]
LDD COUNT // increment COUNT starts here
INC ACC // [1]
STO COUNT //
CMP MAX // is COUNT = MAX?
[1]
JPN LOOP2 // if FALSE, jump to LOOP2
END // end of program [1]
COUNT:
MAX: 4
NAME: B01000110 // ASCII code in binary for 'F'
B01010010 // ASCII code in binary for 'R'
B01000101 // ASCII code in binary for 'E'
B01000100 // ASCII code in binary for 'D'
[Max 15]

© 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

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills May/June 2017
PRE-RELEASE MATERIAL
* 6 8 2 1 8 0 4 0 7 1 *

No Additional Materials are required.


This material should be given to the relevant teachers and candidates as soon as it has been received
at the Centre.

READ THESE INSTRUCTIONS FIRST

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.

This document consists of 12 printed pages.

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

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.

Questions on the examination paper may ask the candidate to write:

• structured English
• pseudocode
• program code

A program flowchart should be considered as an alternative to pseudocode for the documenting of an


algorithm design.

Candidates should be confident with:

• the presentation of an algorithm using either a program flowchart or pseudocode


• the production of a program flowchart from given pseudocode and vice versa.

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.

DECLARE <identifier> : <data type>

If Python is the chosen language, each variable’s identifier (name) and its intended data type must be
documented using a comment statement.

Structured English – Variables

An algorithm in pseudocode uses variables, which should be declared. An algorithm in structured


English does not always use variables. In this case, the candidate needs to use the information given
in the question to complete an identifier table. The table needs to contain an identifier, data type and
description for each variable.

© UCLES 2017 9608/41/PRE/M/J/17


3

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:

• one or more questions, up to a maximum of 10 questions


• the maximum number of marks for the test
• the level (A, S, G)

For each question, the following are to be stored:

• the question text


• the answer
• the maximum number of marks
Key focus: Object-oriented programming
• the topic

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

Explain what containment means in the context of OOP.

Investigate what other information this diagram conveys.

TASK 1.2

Write object-oriented program code to implement the classes.

Remember to use validation and error trapping where appropriate.

© UCLES 2017 9608/41/PRE/M/J/17 [Turn over


4

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.

© UCLES 2017 9608/41/PRE/M/J/17


5

Notes:

# denotes immediate addressing


B denotes a binary number, for example, B01001010
& denotes a hexadecimal number, for example, &4A

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

Key focus: Low-level programming

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.

© UCLES 2017 9608/41/PRE/M/J/17 [Turn over


6

TASK 2.1

X A + B
END

Instruction
Label Op Comment
Operand
code

START: // load the content of A into ACC

// add the content of B to content of ACC

// store content of ACC at address X

END // end of program

X:

A: 5

B: 3

© UCLES 2017 9608/41/PRE/M/J/17


7

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

// compare the content of ACC with content of A

// if not equal (FALSE), jump to ELSE

THEN: // instruction for the THEN part goes here

JMP ENDIF // jump over the ELSE part

ELSE: // instructions for ELSE part start here

ENDIF: END // end of program

A: 65

X: 67

Note: the built-in function CHR(X) returns the character that is represented by the ASCII code held
in X.

© UCLES 2017 9608/41/PRE/M/J/17 [Turn over


8

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

// is content of ACC = content of A ?

// if not equal (FALSE), jump to LOOP

END // end of program

X: 90

A: 65

© UCLES 2017 9608/41/PRE/M/J/17


9

TASK 2.4

FOR COUNT 1 TO 4
OUTPUT CHARS[COUNT]
ENDFOR
END

Instruction
Label Op Comment
Operand
code

// set ACC to 1

// store contents of ACC in COUNT

// set IX to 0

LOOP: // COUNT = 4 + 1 ? starts here

// if equal (TRUE), jump to ENDFOR

// instructions to be repeated start here

// increment IX

// increment COUNT starts here

// jump to LOOP

ENDFOR: END // end of program

COUNT:

CHARS: 72 // 'H'

69 // 'E'

76 // 'L'

80 // 'P'

© UCLES 2017 9608/41/PRE/M/J/17 [Turn over


10

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

// output CHARS[B] starts here

// increment B starts here

// jump back to start of while loop


END // end of program
FORCOUNT: // control variable for inner loop
X: 4
B: 0
CHARS: 72 // 'H'
69 // 'E'
76 // 'L'
80 // 'P'

© UCLES 2017 9608/41/PRE/M/J/17


11

TASK 2.6

Output a string using indirect addressing.

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

// load content of address 100

// increment ACC

// store content of ACC at address 100

// is content of ACC = 107 ?

// if not equal (FALSE), jump to LOOP

END // end of program

100 102

101

102 77 // 'M'

103 65 // 'A'

104 84 // 'T'

105 72 // 'H'

106 83 // 'S'

107

© UCLES 2017 9608/41/PRE/M/J/17 [Turn over


12

TASK 2.7

Programmers use bitwise operations (AND, OR, XOR) to set or examine specific bits.

Example:

Instruction
Label Op Comment
Operand
code

START: 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

END // end of program

X: B10101111

Y: // what does the value of Y tell you about X ?

MASK: B00000001

Write simple programs using the different bitwise operations (AND, OR, XOR) and different MASK content.

Identify the operation and MASK bit pattern to:


• set a bit to 1, leaving all other bits unchanged
• set a bit to 0, leaving all other bits unchanged
• test whether a specific bit is 1
• test whether a specific bit is 0.

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.

© UCLES 2017 9608/41/PRE/M/J/17


Cambridge International Examinations
Cambridge International Advanced Subsidiary and Advanced Level
* 5 0 1 0 7 4 8 6 1 4 *

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills May/June 2017
2 hours
Candidates answer on the Question Paper.
No Additional Materials are required.
No calculators allowed.

READ THESE INSTRUCTIONS FIRST

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.

Answer all questions.


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.

The maximum number of marks is 75.

This document consists of 15 printed pages and 1 blank page.

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.

(a) A programmer writes a program that:

• reads a character from the keyboard (assume it will be a capital letter)


• outputs the alphabetical sequence of characters from ‘A’ to the character input. For
example, if the character ‘G’ is input, the output is:

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.

© UCLES 2017 9608/41/M/J/17


3

Complete the following program. Use op codes from the given instruction set.

Label Op code Operand Comment


START: // INPUT character

// store in CHAR

// Initialise ACC (ASCII value for 'A' is 65)

// OUTPUT ACC

// compare ACC with CHAR

// if equal jump to end of FOR loop

// increment ACC

// jump to LOOP

ENDFOR: END

CHAR:

[8]

(b) The programmer now starts to write a program that:

• 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.

Label Op code Operand Comment


START:

MASK // set to zero all bits except sign bit

// compare with 0

// if not equal jump to ELSE

THEN: // load ACC with 'P' (ASCII value 80)

JMP ENDIF

ELSE: // load ACC with 'N' (ASCII value 78)

ENDIF:

END

NUMBER: B00000101 // integer to be tested

MASK: // value of mask in binary

[7]
© UCLES 2017 9608/41/M/J/17 [Turn over
4

2 A hash table has these associated operations:

• create hash table


• insert record
• search hash table

A hash table is to be used to store customer records.

Each record consists of a unique customer ID, the record key, and other customer data.

(a) The following pseudocode declares a customer record structure.

TYPE CustomerRecord
CustomerID : INTEGER
Data : STRING
ENDTYPE

The hash table is to be implemented as a 1D array Customer with elements indexed


0 to 199. The procedure to create a hash table will declare and initialise the array by storing
200 records with the CustomerID field in each record set to 0.

Complete the pseudocode.

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.

(i) The procedure, InsertRecord, takes as a parameter the customer record to be


inserted into the hash table.

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.

© UCLES 2017 9608/41/M/J/17


5

Complete the pseudocode for the procedure.

PROCEDURE InsertRecord(BYVALUE NewCustomer : CustomerRecord)

TableFull FALSE

// generate hash value

Index ..................................................................................................................

Pointer Index // initialise Pointer variable to hash value

// find a free table element

WHILE ........................................................................................................................

Pointer .......................................................................................................

// wrap back to beginning of table if necessary

IF ........................................................................................................................

THEN

.................................................................................................................

ENDIF

// check if back to original index

IF ........................................................................................................................

THEN

TableFull TRUE

ENDIF

ENDWHILE

IF ..............................................................................................................................

THEN

........................................................................................................................

ELSE

........................................................................................................................

ENDIF

ENDPROCEDURE [9]

© UCLES 2017 9608/41/M/J/17 [Turn over


6

(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.

Complete the pseudocode for the function.

FUNCTION SearchHashTable(BYVALUE SearchID : INTEGER) RETURNS INTEGER

// generate hash value

Index ..................................................................................................................

// check each record from index until found or not there

WHILE ( ....................................................................................................................)

AND (..................................................................................................................)

..............................................................................................................................

// wrap if necessary

IF ........................................................................................................................

THEN

.................................................................................................................

ENDIF

ENDWHILE

// has customer ID been found ?

IF ..............................................................................................................................

THEN

........................................................................................................................

ELSE

........................................................................................................................

ENDIF

ENDFUNCTION [9]

(iii) A record that is no longer required is deleted.

State the problem that might be caused by this deletion.

...........................................................................................................................................

.......................................................................................................................................[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:

NameList : Array[0 : 100] OF STRING

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:

• Name, the string to be searched for


• Start, the index of the first item in the list to be searched
• Finish, the index of the last item in the list to be searched

The function will return the position of the name in the list, or −1 if the name is not found.

Complete the pseudocode for the recursive function.

FUNCTION Find(BYVALUE Name : STRING, BYVALUE Start : INTEGER,


BYVALUE Finish : INTEGER) RETURNS INTEGER

// base case

IF .............................................................................................................................................

THEN

RETURN −1

ELSE

Middle ..................................................................................................................

IF ................................................................................................................................

THEN

RETURN ...........................................................................................................

ELSE // general case

IF SearchItem > .........................................................................................

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

The ADT is to be implemented using object-oriented programming as a linked list of nodes.

Each node consists of data and a pointer.

(a) There are two classes, LinkedList and Node.

(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]

© UCLES 2017 9608/41/M/J/17


9

(b) The design for the Node class consists of:

• 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.

Write program code for:

• the Node class declaration


• the constructor.

Programming language used ...................................................................................................

Program code

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...............................................................................................................................................[5]
© UCLES 2017 9608/41/M/J/17 [Turn over
10

(c) The identifier table for the LinkedList class is:

Identifier Data type Description


HeadPointer INTEGER Pointer to the first node in the ordered list.
FreeListPointer INTEGER Pointer to the first node in the free list.
NodeArray ARRAY[0 : 7] OF Node 1D array stores the nodes that make the
ordered linked list. The unused nodes are
linked together into a free list.
Constructor() Constructor instantiates an object
of LinkedList class, initialises
HeadPointer to be a null pointer and links
all nodes to form the free list.
FindInsertionPoint() Procedure that takes the new data item as
the parameter NewData and returns two
parameters:
• PreviousPointer, whose value is:
either pointer to 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 a
pointer to node after the insertion point.
AddToList(NewString) Procedure that takes as a parameter a
unique string and links it into the correct
position in the ordered list.
OutputListToConsole() Procedure to output all the data from the list
pointed to by HeadPointer.

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

The symbol O represents a null pointer.

(i) Explain the meaning of the term null pointer.

...........................................................................................................................................

.......................................................................................................................................[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.

Programming language used ............................................................................................

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.

Programming language used ............................................................................................

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.

Write program code for this method.

Programming language used ............................................................................................

Program code

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

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

© UCLES 2017 9608/41/M/J/17


14

(vi) The structured English for the AddToList(NewString) method is as follows:

Make a copy of the value of free list pointer, name it NewNodePointer

Store new data item in free node pointed to by NewNodePointer

Adjust free list pointer to point to next free node

IF linked list is currently empty

THEN

Make this node the first node

Set pointer of this node to null pointer

ELSE

Find insertion point using the FindInsertionPoint method

// FindInsertionPoint provides

// pointer to previous node and pointer to next node

IF previous pointer is null pointer

THEN

Link this node to front of list

ELSE

Link this node between previous node and next node

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.

© UCLES 2017 9608/41/M/J/17


15

Write program code for the AddToList method.

Programming language used ............................................................................................

Program code

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.......................................................................................................................................[6]
© UCLES 2017 9608/41/M/J/17
Cambridge International Examinations
Cambridge International Advanced Subsidiary and Advanced Level

COMPUTER SCIENCE 9608/41


Paper 4 Written Paper May/June 2017
MARK SCHEME
Maximum Mark: 75

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.

® IGCSE is a registered trademark.

This document consists of 13 printed pages.

© UCLES 2017 [Turn over


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2017
PUBLISHED

Question Answer Marks

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:

1(b) START: LDD NUMBER 1 7


// set to zero all
AND MASK bits except sign 1
bit
CMP #0 // compare with 0 1
// if not equal jump
JPN ELSE 1
to ELSE
// load ACC with 'P'
THEN: LDM #80 1
(ASCII value 80)
JMP ENDIF
// load ACC with 'N'
ELSE: LDM #78
(ASCII value 78)
ENDIF: OUT //output character 1
END
// integer to be
NUMBER: B00000101
tested
// show value of
MASK: B10000000 mask in binary 1
here

© UCLES 2017 Page 2 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2017
PUBLISHED

Question Answer Marks

2(a) 1 mark for the declaration of the array. 4


1 mark for assigning a 0 to Customer ID (CustomerID ← 0)
1 mark for getting the correct record (Customer[x].)
1 mark for setting up a loop to go from 0 to 199

DECLARE Customer : ARRAY[0 : 199] OF CustomerRecord 1

FOR x ← 0 TO 199 1

Customer[x].CustomerID ← 0 1+1

ENDFOR

2(b)(i) PROCEDURE InsertRecord(BYVAL NewCustomer : CustomerRecord) 9


TableFull ← FALSE
// generate hash value
Index ← Hash(NewCustomer.CustomerID) 1
Pointer ← Index // take a copy of index

// find a free table element


WHILE Customer[Pointer].CustomerID > 0 1
Pointer ← Pointer + 1 1
// wrap back to beginning of table if necessary
IF Pointer > 199 1
THEN
Pointer ← 0 1
ENDIF
// check if back to original index
IF Pointer = Index 1
THEN
TableFull ← TRUE
ENDIF
ENDWHILE
IF NOT TableFull 1
THEN
Customer[Pointer] ← NewCustomer 1
ELSE
OUTPUT "Error" 1
ENDIF
ENDPROCEDURE

© UCLES 2017 Page 3 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2017
PUBLISHED

Question Answer Marks

2(b)(ii) FUNCTION SearchHashTable(BYVAL SearchID : INTEGER) RETURNS 9


INTEGER
// generate hash value
Index ← Hash(SearchID) 1
// check each record from index until found or not there
WHILE (Customer[Index].CustomerID <> SearchID) 1
AND (Customer[Index].CustomerID > 0) 1
Index ← Index + 1 1
// wrap if necessary
IF Index > 199 1
THEN
Index ← 0 1
ENDIF
ENDWHILE
// has customer ID been found?

IF Customer[Index].CustomerID = SearchID 1
THEN
RETURN Index 1
ELSE
RETURN -1 1
ENDIF
ENDFUNCTION

2(b)(iii) A record out of place may not be found 1

© UCLES 2017 Page 4 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2017
PUBLISHED

Question Answer Marks

3 FUNCTION Find(BYVAL Name : STRING, 7


BYVAL Start : INTEGER,
BYVAL Finish : INTEGER) RETURNS INTEGER
// base case
IF Finish < Start 1
THEN
RETURN -1
ELSE
Middle ← (Start + Finish) DIV 2 1
IF NameList[Middle] = Name 1
THEN
RETURN Middle 1
ELSE // general case
IF SearchItem > NameList[Middle] 1
THEN
Find(Name, Middle + 1, Finish) 1
ELSE
Find(Name, Start, Middle - 1) 1
ENDIF
ENDIF
ENDIF
ENDFUNCTION

Question Answer Marks

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

© UCLES 2017 Page 5 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2017
PUBLISHED

Question Answer Marks

4(b) mark as follows: 5


• Class heading and ending
• Constructor heading and ending
• Parameters in constructor heading
• Declaration of (private) attributes : Pointer, Data
• Assignment of parameters to Pointer and Data

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

4(c)(i) A pointer that doesn’t point to any data/node/address 1

© UCLES 2017 Page 6 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2017
PUBLISHED

Question Answer Marks

4(c)(ii) –1 (accept NULL) 2


The array only goes from 0 to 7 // the value is not an array index

4(c)(iii) mark as follows: Max 7


• Class and constructor heading and ending
• Declare private attributes (HeadPointer, FreeListPointer, NodeArray)
• Initialise HeadPointer to null
• Initialise FreeListPointer to 0
• Looping 8 times
• Creating empty node in NodeArray
• Use .SetPointer method to point each new node to next node
• Set last node pointer to null pointer

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;

© UCLES 2017 Page 7 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2017
PUBLISHED

Question Answer Marks

Example VB.NET
Class LinkedList 1
Private HeadPointer As Integer
Private FreeList As Integer
Private NodeArray(7) As Node

Public Sub New() 1


HeadPointer = -1 1
FreeList = 0 1
For i = 0 To 7 1
NodeArray(i) = New Node("", (i + 1)) 1
Next
NodeArray(7).SetPointer(-1) 1
End Sub
End Class

4(c)(iv) • Creating instance of LinkedList assigned to contacts 1

Python Example
contacts = LinkedList()

Pascal Example
var contacts : LinkedList;
contacts := LinkedList.Create;

VB.NET Example
Dim contacts As New LinkedList

© UCLES 2017 Page 8 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2017
PUBLISHED

Question Answer Marks

4(c)(v) mark as follows: 5


• Start with HeadPointer
• Output node data
• Loop until null pointer
• Following pointer to next node
• Use of getter (ie GetData/GetPointer)

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

Public Sub OutputListToConsole()


Dim Pointer As Integer
Pointer = HeadPointer 1
Do While Pointer <> -1 1
Console.WriteLine(NodeArray(Pointer).GetData) 1+1
Pointer = NodeArray(Pointer).GetPointer 1
Loop
End Sub

© UCLES 2017 Page 9 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2017
PUBLISHED

Question Answer Marks

4(c)(vi) mark as follows: Max 6


• Store free list pointer as NewNodePointer
• Store new data item in free node
• Adjust free pointer
• F list is currently empty
• Make the node the first node
• Set pointer of this node to Null Pointer
• Find insertion point
• If previous pointer is Null pointer
• Link this node to front of list
• Link new node between Previous node and next node

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)

© UCLES 2017 Page 10 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2017
PUBLISHED

Question Answer Marks

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;

© UCLES 2017 Page 11 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2017
PUBLISHED

Question Answer Marks

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

© UCLES 2017 Page 12 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2017
PUBLISHED

Question Answer Marks

Pseudocode for reference:

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

© UCLES 2017 Page 13 of 13


Cambridge International Examinations
Cambridge International Advanced Subsidiary and Advanced Level

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills October/November 2017
PRE-RELEASE MATERIAL
* 2 3 8 5 8 6 7 3 7 3 *

This material should be given to the relevant teachers and candidates as soon as it has been received
at the Centre.

READ THESE INSTRUCTIONS FIRST

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.

This document consists of 6 printed pages and 2 blank pages.

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.

Questions on the examination paper may ask the candidate to write:


• structured English
• pseudocode
• program code

A program flowchart should be considered as an alternative to pseudocode for documenting an


algorithm design.

Candidates should be confident with:


• the presentation of an algorithm using either a program flowchart or pseudocode
• the production of a program flowchart from given pseudocode or vice versa

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.

DECLARE <identifier> : <data type>

If Python is the chosen language, each variable’s identifier (name) and its intended data type must be
documented using a comment statement.

Structured English – Variables

An algorithm in pseudocode uses variables, which should be declared. An algorithm in structured


English does not always use variables. In this case, the candidate needs to use the information given
in the question to complete an identifier table. The table needs to contain an identifier, data type and
description for each variable.

© UCLES 2017 9608/41/PRE/O/N/17


3

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

Add additional clauses to this knowledge base.

TASK 1.2

Write a query to find the mother of a person.

TASK 1.3

Write a query to find the father of a person.

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

Write a query to find the grandparents of a person.

TASK 1.7

Explain the difference between the following two clauses.

• parent(richard, james).
• parent(james, richard).

© UCLES 2017 9608/41/PRE/O/N/17 [Turn over


4

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.

© UCLES 2017 9608/41/PRE/O/N/17


5

Notes:

# denotes immediate addressing


B denotes a binary number, for example B01001010
& denotes a hexadecimal number, for example &4A

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.

© UCLES 2017 9608/41/PRE/O/N/17 [Turn over


6

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.

Activity Description Weeks to complete Dependent on

© UCLES 2017 9608/41/PRE/O/N/17


Cambridge International Examinations
Cambridge International Advanced Subsidiary and Advanced Level
* 4 1 3 5 4 4 4 9 1 5 *

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills October/November 2017
2 hours
Candidates answer on the Question Paper.
No Additional Materials are required.
No calculators allowed.

READ THESE INSTRUCTIONS FIRST

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.

Answer all questions.


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.

The maximum number of marks is 75.

This document consists of 16 printed pages.

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.

Current state Event Next state


Closed Temperature rises above 20 °C Half Open
Half Open Temperature drops below 15 °C Closed
Half Open Temperature rises above 30 °C Fully Open
Fully Open Temperature drops below 25 °C Half Open

Complete the state-transition diagram for the window:

.................................
.................................

.........................
.........................
.........................
.........................

.................................
.................................
.................................
.................................

.................................
.................................

.........................
.........................

[7]

© UCLES 2017 9608/41/O/N/17


3

2 (a) (i) State how repetition is shown in a Jackson Structured Programming (JSP) structure
diagram.

...........................................................................................................................................

.......................................................................................................................................[1]

(ii) State how selection is shown in a JSP structure diagram.

...........................................................................................................................................

.......................................................................................................................................[1]

(b) A simple calculator is to be created.

The calculator is to be used as follows:

• User inputs 2 numbers (x and y).


• User inputs an operator (+, –, * or / ).
• The calculator computes the answer.
• The calculator displays the answer.

Draw a JSP diagram for the calculator. The first element is provided.

Calculator

[5]

© UCLES 2017 9608/41/O/N/17 [Turn over


4

3 A declarative programming language is used to represent the following knowledge base:

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).

These clauses have the following meanings:

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.

Write additional clauses to represent this information.

17 .............................................................................................................................................

18 .............................................................................................................................................

19 .............................................................................................................................................

20 .............................................................................................................................................

21 .............................................................................................................................................
[5]

© UCLES 2017 9608/41/O/N/17


5

(b) Using the variable PersonName, the goal:

likes(PersonName, pizza).

returns:

PersonName = jane, ahmed .

Write the result that is returned by the goal:

likes(ahmed, FoodItem).

FoodItem = ............................................................................................................................

...............................................................................................................................................[2]

(c) B might like A, if B is a person, A is a food and B does not dislike A.

Write this as a rule.

might_like(.................................................. , ..................................................)

IF .............................................................................................................................................

...................................................................................................................................................

...............................................................................................................................................[6]

© UCLES 2017 9608/41/O/N/17 [Turn over


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.

© UCLES 2017 9608/41/O/N/17


7

(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 “*”.

The following is pseudocode for this program.

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.

Label Op code Operand Comment


START: LDM #63 // load ASCII value for '?'
// OUTPUT '?'
// input GUESS
// compare with stored letter
// if correct guess, go to GUESSED

// 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]

© UCLES 2017 9608/41/O/N/17 [Turn over


8

(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.

Label Op code Operand Comment


START: // initialise the Index Register
// load the value from NUMBERS
// multiply by 4
// store the new value in NUMBERS
// increment the Index Register

// increment COUNT

// is COUNT = 5 ?
// repeat for next number
ENDP: END
COUNT: 0
NUMBERS: 22
13
5
46
12
[10]

© UCLES 2017 9608/41/O/N/17


9

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.

© UCLES 2017 9608/41/O/N/17 [Turn over


10

5 Large development projects require careful resource management.

(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.

Name the type of testing required at this stage.

...........................................................................................................................................

.......................................................................................................................................[1]

(ii) Name the final testing stage required before the system becomes operational.

...........................................................................................................................................

.......................................................................................................................................[1]

© UCLES 2017 9608/41/O/N/17


11

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.

The following is an example of part of the grid.

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'):

• the animal’s score increases by 1


• the food disappears
• one new animal ('A') is randomly generated and added to the grid (to a maximum of
20 animals)
• one new food ('F') is randomly generated and added to the grid.

The simulation is to be implemented using object-oriented programming.

The programmer has designed two classes, Desert and Animal.

The Desert class consists of:

• 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.

Identifier Data type Description


Instantiate an object of the Animal
class
• Generate a pair of random numbers
Constructor() between 0 and 39.
• Place animal at that random
position.
• Initialise the animal’s score to 0.
• Delete the food.
• Increase the score of the animal that
called the method.
EatFood() • Call the GenerateFood method of
the Desert class.
• Call the Constructor method of
the Animal class.
• Call the
GenerateChangeInCoordinate
method for each coordinate (across
or down number) of the animal’s
Move()
position.
• Moves the animal to the new space.
• If there is food in the new position,
call the EatFood method.
Score INTEGER Initialised to 0
Across INTEGER The across value, between 0 and 39
Down INTEGER The down value, between 0 and 39

© UCLES 2017 9608/41/O/N/17


13

(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.

You should also write:

• the constructor for the class


• set and get methods for the Across attribute only.

Programming language ............................................................................................................

Program code

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...............................................................................................................................................[6]

© UCLES 2017 9608/41/O/N/17 [Turn over


14

(b) The Constructor method of the Desert class:

• initialises an empty grid


• creates 5 animal objects which are added to the AnimalList (an array of animal objects
currently on the grid)
• generates one food
• sets the StepCounter to 0.

Write program code for the Constructor method.

Programming language ............................................................................................................

Program code

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

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

© UCLES 2017 9608/41/O/N/17


15

(c) (i) The function GenerateChangeInCoordinate:

• receives a coordinate (across or down number) as a parameter


• checks whether the coordinate’s value is at a boundary of the grid
• returns a random change (–1, 0 or 1) that will keep the animal’s position within the
grid.

Write program code for the GenerateChangeInCoordinate function.

Programming language .....................................................................................................

Program code

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.......................................................................................................................................[4]

© UCLES 2017 9608/41/O/N/17 [Turn over


16

(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.

Write program code for the Move method.

Programming language .....................................................................................................

Program code

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.......................................................................................................................................[4]

(d) The programmer plans to add a graphic display to the program. The programmer will make
use of a program library.

Explain what is meant by 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.

© UCLES 2017 9608/41/O/N/17


9608/41 Cambridge International AS/A Level – Mark Scheme October/November
PUBLISHED 2017
Question Answer Marks

1 1 mark for each completed statement 7

Temperature > 20° C

Window
Window half
closed open

Temperature < 15 °C Temperature > 30°C

Temperature < 25° C

Question Answer Marks

2(a)(i) • Asterisk (*) in the corner/top of the box(es) 1

2(a)(ii) • Circle (o) in the corner/top of box(es) 1

© UCLES 2017 Page 2 of 15


9608/41 Cambridge International AS/A Level – Mark Scheme October/November
PUBLISHED 2017
Question Answer Marks

2(b) 1 mark per bullet 5


• Inputting 2 numbers, stored in x and y
• Inputting sign Selection used for all four calculations
• .. underneath an appropriate box at level 1
• Displaying the answer

For example:

Calculator

Display
Input x y Input sign Calculaon
answer

answer =
x+y

answer =
x–y

answer =
x*y

answer =
x/y

© UCLES 2017 Page 3 of 15


9608/41 Cambridge International AS/A Level – Mark Scheme October/November
PUBLISHED 2017
Question Answer Marks

3(a) 1 mark per clause 5


• person(mimi).
• food(lettuce).
• likes(mimi, chocolate).
• dislikes(mimi, sushi).
• dislikes(mimi, lettuce).

3(b) 1 mark per answer 2


chocolate, pizza

3(c) 1 mark per bullet 6


• might_like(B,A)
• Person(B)
• Food(A)
• AND
• AND NOT
• Dislikes predicate

For example:

might_like(B, A).

IF person(B) AND food(A)

AND NOT(dislikes(B, A)).

© UCLES 2017 Page 4 of 15


9608/41 Cambridge International AS/A Level – Mark Scheme October/November
PUBLISHED 2017
Question Answer Marks

4(a) Label Op code Operand Comment Marks 11

START: LDM #63 // load ASCII value for '?'

OUT // OUTPUT '?' 1

IN // input GUESS 1

CMP LETTERTOGUESS // compare with stored letter 1

JPE GUESSED // if correct guess, go to 1


GUESSED
LDD ATTEMPTS // increment ATTEMPTS 1
INC ACC 1

STO ATTEMPTS 1

CMP #9 // is ATTEMPTS = 9 ? 1

JPE ENDP // if out of guesses, go to ENDP 1

JMP START // go back to beginning of loop 1

GUESSED: LDM #42 // load ASCII for '*'

OUT // OUTPUT '*' 1

ENDP: END // end program

ATTEMPTS: 0

LETTERTOGUESS: 'a'

© UCLES 2017 Page 5 of 15


9608/41 Cambridge International AS/A Level – Mark Scheme October/November
PUBLISHED 2017
Question Answer Marks

4(b) Label Opcode Operand Comment Mark 10

START: LDR #0 // initialise the Index Register 1


LOOP: LDX NUMBERS // load the value from NUMBERS 1 (LOOP) +
1(LDX NUMBERS)
LSL #2 // multiply by 4 1 (LSL) +
1 (#2)
STX NUMBERS // store the new value in NUMBERS 1
INC IX // increment the Index Register 1
LDD COUNT
INC ACC // increment COUNT 1
STO COUNT
CMP #5 // is COUNT = 5 ? 1
JPN LOOP // repeat for next number 1
ENDP: END
COUNT: 0
NUMBERS: 22
13
5
46
12

© UCLES 2017 Page 6 of 15


9608/41 Cambridge International AS/A Level – Mark Scheme October/November
PUBLISHED 2017
Question Answer Marks

5(a)(i) PERT / GANTT 1

5(a)(ii) 1 mark per bullet to max 3 3


For example:
• Calculate total minimum time required for project
• Identify milestones
• Task dependencies
• Provides the critical path analysis
• Identify which tasks need to be prioritised
• Determine when to begin specific tasks/stages
• Identify slack time
• Identify when resources need allocating
• Identify tasks that can be completed in parallel

5(b)(i) Integration 1

5(b)(ii) Beta / acceptance 1

Question Answer Marks

6(a) 1 mark per bullet to max 6 6


• Declaring a class with the name animal
• Declaring variables for across, down and score (all Integers)
• «as private/protected
• Correct constructor header and ending
• Randomly generating an across between 0–39 inc. in constructor
• Randomly generating a down between 0–39 inc. in constructor
• Initialising Score to zero in constructor

• Correct get for Across


• Correct set for Across

© UCLES 2017 Page 7 of 15


9608/41 Cambridge International AS/A Level – Mark Scheme October/November
PUBLISHED 2017
Question Answer Marks

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

© UCLES 2017 Page 8 of 15


9608/41 Cambridge International AS/A Level – Mark Scheme October/November
PUBLISHED 2017
Question Answer Marks

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

© UCLES 2017 Page 9 of 15


9608/41 Cambridge International AS/A Level – Mark Scheme October/November
PUBLISHED 2017
Question Answer Marks

6(a) Example: Pascal


type
Animal = class
private
Across: integer;
Down: integer;
score: integer;
public
constructor init;

procedure SetAcross(AcrossV: integer);


function GetAcross(): integer;
end;

constructor Animal.init();
SetAcross(random(40));
SetDown (random(40));
SetScore (0);
end;

procedure Animal.SetAcross(AcrossV: integer);


begin
Across := AcrossV;
end;

function Animal.GetAcross(): integer;


begin
GetAcross := Across;
end;

© UCLES 2017 Page 10 of 15


9608/41 Cambridge International AS/A Level – Mark Scheme October/November
PUBLISHED 2017
Question Answer Marks

6(b) 1 mark per bullet to max 5 5


• constructor method heading and ending
• Initialise all 40 by 40 elements of Grid as '' or equivalent
• Loop 5 times«
• «Creates a new instance of animal inside loop...
• ...and adds it to array AnimalList

• Call generate food and initialise StepCounter to 0

Example Python

def __init__ (self) :


self.grid = [[' ' for i in range(40)] for j in range(40)]
self.AnimalList = []
self.StepCounter = 0
for i in range(5) :
newAnimal = Animal ()
self.AnimalList.append(newAnimal)
self.GenerateFood()

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

6(b) Example Pascal

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) 1 mark per bullet: max 4


• Function header and ending taking one value as parameter
• Check if coordinate = 0 (on lower bound)
• «generate random number (0 or 1)
• Check if coordinate = 39 (on upper bound)
• «generate random number (–1 or 0)
• Generate random number (e.g. –1, 0, 1)
• Return the generated value

© UCLES 2017 Page 12 of 15


9608/41 Cambridge International AS/A Level – Mark Scheme October/November
PUBLISHED 2017
Question Answer Marks

6(c)(i) Example VB

Function GenerateDirection(ByRef coord As Integer)


Dim lowerbound As Integer = -1
Dim upperbound As Integer = 1

If coord = 0 Then
lowerbound = 0
ElseIf coord = 39 Then
upperbound = 0
End If

GenerateDirection = randomnumber.Next(lowerbound, upperbound)

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)

© UCLES 2017 Page 13 of 15


9608/41 Cambridge International AS/A Level – Mark Scheme October/November
PUBLISHED 2017
Question Answer Marks

6(c)(i) Example Pascal

function GenerateDirection(coord : Integer): Integer;


begin
lowerbound = -1;
upperbound = 1;
if coord = 0 then
lowerbound = 0;
else if coord = 39 then
upperbound = 0;
GenerateDirection = random(39);
end;

6(c)(ii) 1 mark per bullet to max 4 4


• Procedure move header, no parameters
• Calling GenerateDirection twice sending across and down as separate parameters
• Add return value to Across
• Add return value to Down
• Check if the grid, at the (new) coordinates == “F”
• ..if true, Call EatFood

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

© UCLES 2017 Page 14 of 15


9608/41 Cambridge International AS/A Level – Mark Scheme October/November
PUBLISHED 2017
Question Answer Marks

6(c)(ii) Example VB

Sub Move(ByRef thisAnimal As Animal)


thisAnimal.across += GenerateChangeInCoordinate (thisAnimal.across)
thisAnimal.down += GenerateChangeInCoordinate (thisAnimal.down)
If thegrid._grid(thisAnimal.across, thisAnimal.down) = "F"
Then
Call EatFood()
End If
End Sub

Example Pascal

procedure Move(thisAnimal : Animal);


begin
thisAnimal.across = this.Animal.across + GenerateChangeInCoordinate
(thisAnimal.across);
thisAnimal.down = thisAnimal.down + GenerateChangeInCoordinate (thisAnimal.down);
if (thisgrid.grid(thisAnimal.across, thisAnimal.down) = "F") then
EatFood();
End;

6(d) 1 mark per bullet to max 3 2


• Pre-compiled
• Collection of Code/modules/routines
• Each module performs a specific purpose/task
• Each module can be linked/imported into the program

© UCLES 2017 Page 15 of 15


Cambridge International Examinations
Cambridge International Advanced Subsidiary and Advanced Level

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills May/June 2018
PRE-RELEASE MATERIAL
* 2 3 6 2 7 8 1 9 2 0 *

No Additional Materials are required.


This material should be given to the relevant teachers and candidates as soon as it has been received
at the Centre.

READ THESE INSTRUCTIONS FIRST

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.

This document consists of 8 printed pages.

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.

Questions on the examination paper may ask the candidate to write:

• 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 should be confident with:

• the presentation of an algorithm using either a program flowchart or pseudocode


• the production of a program flowchart from given pseudocode and vice versa
• the production of a JSP structure diagram from a given scenario

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.

DECLARE <identifier> : <data type>

If Python is the chosen language, each variable’s identifier (name) and its intended data type must be
documented using a comment statement.

Structured English – Variables

An algorithm in pseudocode uses variables, which should be declared. An algorithm in structured


English does not always use variables. In this case, the candidate needs to use the information given
in the question to complete an identifier table. The table needs to contain an identifier, data type and
description for each variable.

© UCLES 2018 9608/41/PRE/M/J/18


3

Key focus: JSP structure diagrams


TASK 1

Staff salaries are read from a file. The role of each member of staff is determined by their salary:

• if they earn 50 or less, they are a Manager


• if they earn more than 50 but less than 90 they are a Lead Developer
• if they earn 90 or more, they are a Project Manager.

The following JSP structure diagram shows the structure of a solution for this problem.

Salary
Classification

*
Identify Role

Read Salary Salary > 50

FALSE TRUE

Assign Manager Salary >= 90

FALSE TRUE

Assign Lead Assign Project


Developer Manager

TASK 1.1

Research the purpose of JSP structure diagrams.

TASK 1.2

Find out the meaning of the different symbols inside the boxes and how these affect the structure of
the program.

© UCLES 2018 9608/41/PRE/M/J/18 [Turn over


4

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.

Edit the JSP structure diagram to include the Consultant role.

TASK 1.5

Edit the pseudocode algorithm to add the Consultant role.

TASK 1.6

Write a function in program code to determine the role of a staff member.

The function will take salary as its parameter, and return the role title.

© UCLES 2018 9608/41/PRE/M/J/18


5

Key focus: Object-oriented programming


TASK 2

A toy shop needs a computer system to store information about its toys.

The developer writes a program using object-oriented programming.

• A toy has the properties:

Name (for example, Train engine)


ID (for example, TE11)
Price (for example, 0.99)
Minimum age (for example, 4)

• A computer game is a type of toy; it has the properties of toy, and:

Category (for example, Car racing)


Console (for example, Camstation)

• A vehicle is a type of toy; it has the properties of toy, and:

Type (for example, Car)


Height (for example, 4)
Length (for example, 15)
Weight (for example, 0.2)

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

© UCLES 2018 9608/41/PRE/M/J/18 [Turn over


6

TASK 2.2

Find out what is meant by inheritance.

The ComputerGame and Vehicle classes inherit from the Toy class.

Add arrows to represent the inheritance relationships in your class diagram.

TASK 2.3

Write program code to create the Toy class. Make sure:


Key focus: Writing classes
• the properties are declared as private
• you have a constructor
• you have get and set methods for each property.

TASK 2.4

Write program code to create the ComputerGame and Vehicle classes. Make sure:

• the properties are declared as private


• you have a constructor
• you have get and set methods for each property
• the classes inherit the properties from the Toy class.

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.

Name = "Red Sports Car"


ID = "RSC13"
Price = 15.00 Key focus: Instantiating objects
Minimum age = 6
Type = "Car"
Height = 3.3
Length = 12.1
Weight = 0.08

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.

Write the procedure and test it with appropriate data.

© UCLES 2018 9608/41/PRE/M/J/18


7

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%.

Write the procedure and test it with appropriate data.

TASK 2.9

Research the differences between a bubble sort and insertion sort.

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.

Test the algorithm with appropriate data.


Key focus: Declarative language
TASK 3

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

Add the following facts:

• Habib is a character, who is an explorer.


Key focus: Adding facts

• Habib has a pet fish and the skill of time travel.

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.

© UCLES 2018 9608/41/PRE/M/J/18 [Turn over


8

TASK 3.3

Add additional characters, animals, pets and skills.

TASK 3.4

State what would be returned if the following goals were added.

• character(jim).
• character_type(jenny, X).
• character_type(X, prince).
• has_skill(jenny, X).
• has_skill(X, fly).

TASK 3.5 Key focus: Writing goals

Write goals to find the following information.

• all Jim’s pets


• all the characters who can fly
• all the skills
• all the pets of characters who are princesses

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.

© UCLES 2018 9608/41/PRE/M/J/18


Cambridge International Examinations
Cambridge International Advanced Subsidiary and Advanced Level
* 4 9 0 4 6 8 0 0 5 5 *

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills May/June 2018
2 hours
Candidates answer on the Question Paper.
No Additional Materials are required.
No calculators allowed.

READ THESE INSTRUCTIONS FIRST

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.

Answer all questions.


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.

The maximum number of marks is 75.

This document consists of 17 printed pages and 3 blank pages.

DC (KN) 164472
© UCLES 2018 [Turn over
2

1 A declarative language is used to represent facts and rules about flights.

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).

These clauses have the following meaning:

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.

(a) More facts need to be included.

There is a direct flight from London to Rome and British Air flies to Rome.

14 .............................................................................................................................................

15 .............................................................................................................................................
[2]

(b) Using the variable Q, the goal

flies(Q, fly_jet).

returns

Q = paris, vienna

Write the result returned by the goal

flies(K, ciebe).

K = ........................................................................................................................................[2]

© UCLES 2018 9608/41/M/J/18


3

(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.

Write a rule to represent this condition.

flies(Y, X)

IF .............................................................................................................................................

...............................................................................................................................................[3]

(e) State what the following goal returns.

can_fly(glasgow, rome).

...............................................................................................................................................[1]

© UCLES 2018 9608/41/M/J/18 [Turn over


4

2 The array ItemList[1:20] stores data. A bubble sort sorts these data.

(a) Complete the pseudocode algorithm for a bubble sort.

01 MaxIndex 20

02 NumberItems ........................................................................................................

03 FOR Outer 1 TO ..................................................................................................

04 FOR Inner 1 to NumberItems

05 IF ItemList[Inner] > ..............................................................................

06 THEN

07 Temp ItemList[ ........................................................................]

08 ItemList[Inner] ItemList[ ................................................]

09 ItemList[Inner + 1] .............................................................

10 ENDIF

11 ENDFOR

12 NumberItems ..................................................................................................

13 ENDFOR
[7]

(b) The algorithm in part (a) is inefficient.

(i) Explain why the algorithm in part (a) is inefficient.

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.......................................................................................................................................[2]

(ii) Explain how you would improve the efficiency of this algorithm.

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.......................................................................................................................................[3]

© UCLES 2018 9608/41/M/J/18


5

(c) An insertion sort is another sorting algorithm.

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]

© UCLES 2018 9608/41/M/J/18 [Turn over


6

3 An internet based music streaming service provides access to an unlimited number of songs for
members to play.

The following pseudocode represents the operation of the service.

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]

© UCLES 2018 9608/41/M/J/18


7

(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]

© UCLES 2018 9608/41/M/J/18 [Turn over


8

4 A software company is developing a new application. The project manager has created a work
breakdown structure, as shown in the following table.

Activity Days to complete Predecessor


A Gather user requirements 6
B Design work 8 A
C Develop server code 4 B
D Develop application code 5 B
E User interface development 6 B
F Test server code 2 C
G Test application 2 D,E
H Test application/server integration 5 F,G
I Roll out mobile application 3 H

(a) Use the data in the table to complete the following Program Evaluation Review Technique
(PERT) chart.

........
........ ........ ........

6 8 ........ ........ ........ ........


1 2 3 5 6 7 8
A B ........ ........ ........ ........

........
........

[5]

(b) Calculate the critical path (CP). State the:

activities that form the CP .........................................................................................................

duration of the CP .....................................................................................................................


[2]

(c) For activity F, state the:

earliest start time ......................................................................................................................

latest finish time ........................................................................................................................


[2]
© UCLES 2018 9608/41/M/J/18
10

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 the attributes:

Attribute Description Example value


The x coordinate of the game
PositionX 92
element.
The y coordinate of the game
PositionY 106
element.
Width The width of the game element. 150
Height The height of the game element. 200
The filename of the image file for
ImageFilename GameElementFrame1.png
the game element.

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:

Attribute Description Example value


AnimationFrames An array of GameElement
A string giving the direction the "Left"
Direction
object is travelling in.
A value for the strength that 2000
Strength
indicates the power of the object.
A value for the health that 100
Health
indicates the health of the object.

The player’s character can either move left or right, or jump.

© UCLES 2018 9608/41/M/J/18


11

(a) Complete the following class diagram for the game.

You do not need to include any additional get or set methods.

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]

© UCLES 2018 9608/41/M/J/18 [Turn over


12

(b) Write program code to define the GameElement class.

Programming language ............................................................................................................

Program code

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...............................................................................................................................................[6]

© UCLES 2018 9608/41/M/J/18


13

(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.

Write program code for the Scenery class.

Programming language ............................................................................................................

Program code

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...............................................................................................................................................[6]
© UCLES 2018 9608/41/M/J/18 [Turn over
14

(d) A new scenery object, GiftBox, is to be created.

(i) The attributes of GiftBox are as follows:

Attribute Value
PositionX 150
PositionY 150
Width 50
Height 75
ImageFilename "box.png"
CauseDamage TRUE
DamagePoints 50

Write program code to create an instance of GiftBox.

Programming language .....................................................................................................

Program code

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.......................................................................................................................................[3]

© UCLES 2018 9608/41/M/J/18


15

(ii) An additional method, GetScenery(), returns all the attributes of the Scenery class.

Write program code for the GetScenery() method.

You should use the GetDetails() method that the Scenery class inherits from the
GameElement class.

Programming language .....................................................................................................

Program code

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

.......................................................................................................................................[3]

© UCLES 2018 9608/41/M/J/18 [Turn over


16

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.

An example of a record of ListNode is shown in the following table.

Data Field Value


Player "Alvaro"
Pointer 1

(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

A recursive function traverses the linked list to search for a player.

An example of calling the function, using pseudocode, is:

Position SearchList("Gareth", ListHead)

© UCLES 2018 9608/41/M/J/18


17

Complete the following pseudocode to implement the function SearchList().

The function will return a value of 99 when a player is not found.

FUNCTION SearchList(Find : STRING, Position : INTEGER) RETURNS INTEGER

IF Scorer[Position].Player = ..............................................................................

THEN

RETURN ................................................................................................................

ELSE

IF Scorer[Position].Pointer <> –1

THEN

Position SearchList(Find, ..................................................)

RETURN ...................................................................................................

ELSE

RETURN ...................................................................................................

ENDIF

ENDIF

ENDFUNCTION
[5]

© UCLES 2018 9608/41/M/J/18


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marks

1(a) 1 mark per fact 2

14 direct(london, rome).
15 flies(rome, british_air).

1(b) 1 mark per bullet: 2


• palma
• salzburg

K = palma, salzburg

1(c) 1 mark per bullet: 2


• direct
• glasgow, M

direct(glasgow, M).

1(d) 1 mark per bullet: 3


• flies(Z,X)
• AND
• direct(Z, Y)

flies(Z, X) AND direct(Z, Y)

1(e) YES 1

© UCLES 2018 Page 4 of 19


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marks

2(a) 1 mark for each completed statement 7


01 MaxIndex ← 20
02 NumberItems ← MaxIndex – 1 // 19
03 FOR Outer ← 1 TO MaxIndex – 1 // 19
04 FOR Inner ← 1 to NumberItems
05 IF ItemList[Inner] > ItemList[Inner + 1]
06 THEN
07 Temp ← ItemList[Inner]
08 ItemList[Inner] ← ItemList[Inner + 1]
09 ItemList[Inner + 1] ← Temp
10 ENDIF
11 ENDFOR
12 NumberItems ← NumberItems - 1
13 ENDFOR

2(b)(i) 1 mark per bullet 2

• Iterations continue // it continues doing comparisons


• «after the array is sorted

2(b)(ii) 1 mark per bullet to max 3 3

• Use of a flag to indicate if any swaps have taken place


• If the inner loop has made all comparisons with no changes
• «flag/value set accordingly
• A comparison checks the flag/value at the end of each inner loop
• «if it is sorted it breaks out/stops

© UCLES 2018 Page 5 of 19


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marks

2(c) 1 mark per bullet to max 4 4

e.g.
• When the list is almost sorted «
• «because it will stop as soon as it is sorted

• When there are a large number of data items «


• «because it will perform fewer comparisons/loops

© UCLES 2018 Page 6 of 19


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marks

3(a) 1 mark per bullet 5

• OpenAccount, OperateAccount and Close Account on same level


• RequestCloseAccount under OperateAccount
• «SubscriptionDue under RequestCloseAcount
• «Make Payment and PlaySong under SubscriptionDue
• Correct selection and iteration throughout

© UCLES 2018 Page 7 of 19


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marks

3(b) 1 mark per bullet 4

• 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

© UCLES 2018 Page 8 of 19


960
08/41 Ca
ambridge Interna
ational AS/A Lev
vel – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marrks

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

© UCLES 2018 Page 9 of 19


960
08/41 Ca
ambridge Interna
ational AS/A Lev
vel – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marrks

5(a) 1 ma
ark for each bulle
et: 3

• AnimatedElement attributes
A
• P
Player methods
• Inheritance arrow
ws

© UCLES 2018 Page 10 of 19


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marks

5(b) 1 mark per bullet to max 6 6

• 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

Python example code:

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

© UCLES 2018 Page 11 of 19


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marks

5(b) Visual Basic example code:

Class GameElement
Private PositionX As Integer
Private PositionY As Integer
Private Width As Integer
Private Height As Integer
Private ImageFilename As String

Public Sub New(ByVal X As Integer,ByVal Y As Integer,


ByVal W As Integer, ByVal H As Integer, Filename As String )
PositionX = X
PositionY = Y
Width = W
Height = H
ImageFilename = Filename
End Sub

Public Function GetDetails()


Dim Message As String

Message = "PositionX: " + PositionX + "PositionY: " +


PositionY + ", width: " + Width + ", height: " +
Height + ", ImageFilename:" + ImageFilename
Return Message
End Function

End Class

© UCLES 2018 Page 12 of 19


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marks

5(b) Pascal example code:

type GameElement = 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;

Constructor GameElement.init(X, Y, W, H:Integer; Filename: String);


begin
PositionX := X;
PositionY := Y;
Width := W;
Height := H;
ImageFilename := Filename;
end;

Function GameElement.GetDetails() : String;


var Message:String;
begin
Message = "PositionX: " + PositionX + "PositionY: " + PositionY
+ ", width: " + Width + ", height: " + Height + ",
ImageFilename:" + ImageFilename;
Result = Message
end;

© UCLES 2018 Page 13 of 19


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marks

5(c) Max 4 from each section to max 6 overall 6

1 mark per bullet to max 4

• class declaration with inheritance


• constructor declaration
• «taking all 5 parameters and CauseDamage, DamagePoints parameters
• «with inheritance constructor call
• Declaring CauseDamage, DamagePoints private and assigning parameters

1 mark per bullet to max 4

• Function declaration for GiveDamagePoints «


• «checking if CauseDamage = True
• «returning DamagePoints if true
• «else returning appropriate value e.g. -1/null/blank

Python example code:

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

© UCLES 2018 Page 14 of 19


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marks

5(c) Visual Basic example code:

Class Scenery
Inherits GameElement
Private CauseDamage As Boolean
Private DamagePoints As Integer

Public Sub New(ByVal X As Integer,ByVal Y As Integer, ByVal W As


Integer, ByVal H As Integer,Filename As String,
ByVal CD As Boolean, ByVal DP As Integer)
MyBase.New(X, Y, W, H, Filename)
CauseDamage = CD
DamagePoints = DP
End Sub

Public Function GiveDamagePoints() As Integer


If (CauseDamage) Then
Return DamagePoints
Else
Return 0
End if

End Function
End Class

© UCLES 2018 Page 15 of 19


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marks

5(c) Pascal example code:

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;

© UCLES 2018 Page 16 of 19


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marks

5(d)(i) 1 mark per bullet 3

• Variable GiftBox assigned value


• Call Scenery
• With all 7 parameters assigned correctly

Python example code:

GiftBox = Scenery(150, 150, 50, 75, "box.png", True, 50)

Visual Basic example code:

GiftBox = Scenery(150, 150, 50, 75, "box.png", True, 50)

Pascal example code:


GiftBox := Scenery(150, 150, 50, 75, "box.png", True, 50)

© UCLES 2018 Page 17 of 19


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marks

5(d)(ii) 1 mark per bullet 3


• Function declaration with no parameters
• Use inherited GetDetails method to get string
• Return all values

def GetScenery(self):
Message = Object.GetDetails(self)
Message = Message + " Causes Damage:", self.CauseDamage, “Damage
Points:", self.DamagePoints
return Message

Visual Basic example code:

Public Function GetScenery() As String


Dim Message As String
Message = MyBase.GetDetails()
Message = Message + "CauseDamage: " + CauseDamage + "
DamagePoints: " + DamagePoints
Return Message
End Function

Pascal example code:

Function Secenery.GetScenery(): String


Var Message : String
Begin
Message := GetDetails();
Message := Message + "CauseDamage: " + CauseDamage + "
DamagePoints: " + DamagePoints;
Result:=Message;
End;

© UCLES 2018 Page 18 of 19


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2018
PUBLISHED
Question Answer Marks

6(a)(i) 1 mark per bullet: 3

• TYPE ListNode declaration and ENDTYPE


• DECLARE Player : String
• DECLARE Pointer : INTEGER

TYPE ListNode
DECLARE Player : STRING
DECLARE Pointer : INTEGER
ENDTYPE

6(a)(ii) 1 mark per bullet: 2

• DECLARE Scorers : ARRAY[0:9]


• OF ListNode
DECLARE Scorers : ARRAY[0:9] OF ListNode

6(b) 1 mark for each completed statement 5

FUNCTION SearchList(Find, Position) RETURNS INTEGER


IF Scorer[Position].Player = Find
THEN
RETURN Position
ELSE
IF Scorer[Position].Player <> -1
THEN
Position ← SearchList(Find, Scorer[Position].Pointer)
RETURN Position
ELSE
RETURN 99
ENDIF
ENDIF
ENDPROCEDURE

© UCLES 2018 Page 19 of 19


Cambridge International Examinations
Cambridge International Advanced Subsidiary and Advanced Level

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills October/November 2018
PRE-RELEASE MATERIAL
* 7 0 7 7 7 1 4 6 8 5 *

No Additional Materials are required.


This material should be given to the relevant teachers and candidates as soon as it has been received
at the Centre.

READ THESE INSTRUCTIONS FIRST

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.

This document consists of 7 printed pages and 1 blank page.

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

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.

Questions on the examination paper may ask the candidate to write:

• structured English
• pseudocode
• program code

A program flowchart or the use of Jackson Structured Programming should be considered as an


alternative to pseudocode for the documenting of a high-level algorithm design.

Candidates should be confident with:

• the presentation of an algorithm using either a program flowchart or pseudocode


• the production of a program flowchart from given pseudocode and vice versa
• the production of a JSP structure diagram from a given scenario

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.

DECLARE <identifier> : <data type>

If Python is the chosen language, each variable’s identifier (name) and its intended data type must be
documented using a comment statement.

Structured English – Variables

An algorithm in pseudocode uses variables, which should be declared. An algorithm in structured


English does not always use variables. In this case, the candidate needs to use the information given
in the question to complete an identifier table. The table needs to contain an identifier, data type and
description for each variable.

© UCLES 2018 9608/41/PRE/O/N/18


3

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 program is written using object-oriented programming.

• The class Computer has the properties:

Code (for example, CMP001)


Width (for example, 20.7)
Height (for example, 16.2)
Weight (for example, 1.3)
Make (for example, ciesoft)
Processor (for example, ZX100)
RAM size (for example, 4GB)
Storage size (for example, 200GB)

• The class MobilePhone is a type of computer, it has the properties of the Computer class, and:

Camera (for example, TRUE)


3G (for example, TRUE)
4G (for example, FALSE)
Mobile phone network (for example, CIE Mobile)

• The class Laptop is a type of computer, it has the properties of the Computer class, and:

Touchscreen (for example, FALSE)


Removable screen (for example, TRUE)
Tablet mode (for example, TRUE)
USB 3.0 ports (for example, 2)

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.

© UCLES 2018 9608/41/PRE/O/N/18 [Turn over


4

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.

Add inheritance to your class diagram.

© UCLES 2018 9608/41/PRE/O/N/18


5

TASK 1.4

Write program code to create the Computer class. Make sure:

• the properties are declared as private


• you have a constructor
• you have get and set methods for each property.

TASK 1.5

Write program code to create the MobilePhone and Laptop classes. Make sure:

• the properties are declared as private


• you have a constructor
• you have get and set methods for each property
• the classes inherit the properties from the Computer class.

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

Write a procedure to:

• prompt a user to input the code for a computer


• find the computer with that code
• output the information for the computer in an appropriate format.

© UCLES 2018 9608/41/PRE/O/N/18 [Turn over


6

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

Add the following facts:

• Alex is unemployed with 12 years’ experience.


• Alex is qualified as a typist and an accountant.

TASK 2.2 Key focus:


Adding facts
Add two more people, and four more job vacancies.

TASK 2.3

State what is returned for the following goals.

• qualified_as(sally, B)
• job_vacancy(X, doctor)
• job_vacancy(a_school, art_teacher)
• suitable_job(joe, X)

TASK 2.4 Key focus:


Write goals to find the following information. Writing goals

• all people who are employed


• all people who are first aid trained
• all jobs that one of the people you have added in TASK 2.2 is qualified to do
• all job vacancies at a_school
• all jobs for a maths teacher
• the jobs that Sally and Alex are suitable for

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.

© UCLES 2018 9608/41/PRE/O/N/18


7

TASK 3

A program uses a record structure, Boat, to store information about boats. The record has the fields:

• Boat name (for example, “Mr Boaty”)


• Manufacturer (for example, “Camboats”) Key focus:
• Boat type (for example, “1XSC”) Record structure
TASK 3.1

Use pseudocode to write a definition for the record structure Boat.

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

Create four boats using your record structure, as separate variables.

TASK 3.4 Key focus:


Amend your program, so the boats are stored in a 1D array. Storing records

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

Amend the program to prompt the user to enter a boat name.

Write a procedure to find and output the information about the boat the user has entered.

© UCLES 2018 9608/41/PRE/O/N/18


Cambridge International Examinations
Cambridge International Advanced Subsidiary and Advanced Level
* 2 2 5 8 6 3 3 6 4 9 *

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills October/November 2018
2 hours
Candidates answer on the Question Paper.
No Additional Materials are required.
No calculators allowed.

READ THESE INSTRUCTIONS FIRST

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.

Answer all questions.


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.

The maximum number of marks is 75.

This document consists of 16 printed pages.

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).

11 is_a_mammal(X) IF (feature(X, Y) AND mammal(Y)) AND (feature(X, Z)


AND mammal(Z)).

These clauses are explained in the following table.

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

(a) More facts are to be included.

(i) A bird has wings, and a bird lays eggs.

Write the additional clauses to record these facts.

12 ......................................................................................................................................

13 ......................................................................................................................................
[2]

(ii) An eagle has all the features of a bird.

Write the additional clauses to record this fact.

14 ......................................................................................................................................

15 ......................................................................................................................................
[2]

© UCLES 2018 9608/41/O/N/18


3

(b) (i) Using the variable B, the goal

feature(B, drinks_milk)

returns

B = dog

Write the result returned by the goal

feature(B, lives_in_water)

B = .............................................................................................................................. [2]

(ii) Write a goal, using the variable C, to find the feature(s) of tuna.

...................................................................................................................................... [2]

(c) An animal is a bird if it lays eggs and it has wings.

Complete the following rule.

is_a_bird(X) IF .................................................................................................................

.............................................................................................................................................. [3]

(d) Declarative programming and object-oriented programming are two examples of programming
paradigms.

(i) Define the term programming paradigm.

...........................................................................................................................................

...................................................................................................................................... [1]

(ii) Give two examples of programming paradigms, other than declarative and object-oriented
programming.

1 ........................................................................................................................................

2 ........................................................................................................................................
[2]

© UCLES 2018 9608/41/O/N/18 [Turn over


4

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.

Field name Description


Title The title of the book
Author The first listed author of the book
A 13-digit code that uniquely identifies the book,
ISBN for example:
"0081107546738"
Fiction If the book is fiction (TRUE) or non-fiction (FALSE)
LastRead The date when Kendra last read the book

(a) Write pseudocode to declare an Abstract Data Type (ADT) named Book, to store the
information in the table.

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

.............................................................................................................................................. [4]

© UCLES 2018 9608/41/O/N/18


5

(b) The records are stored in a random access file.

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.

Write program code for the function Hash().

Programming language ............................................................................................................

Program code ...........................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

.............................................................................................................................................. [4]

© UCLES 2018 9608/41/O/N/18 [Turn over


6

(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.

Use pseudocode to write the procedure FindBook().

You can assume that the record exists at the disk address generated.

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................
© UCLES 2018 9608/41/O/N/18
7

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...............................................................................................................................................[8]

© UCLES 2018 9608/41/O/N/18 [Turn over


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.

(a) Describe a stack structure.

...................................................................................................................................................

.............................................................................................................................................. [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

(i) Describe the purpose of the variable StackPointer.

...........................................................................................................................................

...................................................................................................................................... [1]

© UCLES 2018 9608/41/O/N/18


9

(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:

DECLARE Parts : ARRAY[0 : 19] OF STRING

(i) The procedure POP outputs the last element that has been pushed onto the stack and
replaces it with a '*'.

Complete the pseudocode for the procedure POP.

PROCEDURE POP

IF ………………………………. = ……………………………….

THEN

OUTPUT "The stack is empty"

ELSE

StackPointer …………………………………………

OUTPUT ……………………………….……………………………….

Parts[StackPointer] ……………………………….

ENDIF

ENDPROCEDURE
[5]

(ii) The procedure PUSH() puts the parameter onto the stack.

Complete the pseudocode for the procedure PUSH().

PROCEDURE PUSH(BYVALUE Value : String)

IF StackPointer > ……………………………….…

THEN

OUTPUT "Stack full"

ELSE

……………………….………..……… …………….………………….…..

StackPointer ………………………….….…………………………….

ENDIF

ENDPROCEDURE
[4]

© UCLES 2018 9608/41/O/N/18


11

4 The recursive algorithm for the Calculate() function is defined as follows:

01 FUNCTION Calculate(BYVALUE Number : INTEGER) RETURNS INTEGER

02 IF Number = 0

03 THEN

04 Calculate −10

05 ELSE

06 Calculate Number * Calculate(Number − 1)

07 ENDIF

08 ENDFUNCTION

(a) (i) State what is meant by a recursive algorithm.

...........................................................................................................................................

...................................................................................................................................... [1]

(ii) State the line number in Calculate() where the recursive call takes place.

...................................................................................................................................... [1]

Question 4(b) begins on the next page.

© UCLES 2018 9608/41/O/N/18 [Turn over


12

(b) The function is called with Calculate(3).

Dry run the function and complete the trace table below. State the final value returned. Show
your working.

01 FUNCTION Calculate(BYVALUE Number : INTEGER) RETURNS INTEGER

02 IF Number = 0

03 THEN

04 Calculate −10

05 ELSE

06 Calculate Number * Calculate(Number − 1)

07 ENDIF

08 ENDFUNCTION

Working .....................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

Trace table:

Call number Function call Number = 0 ? Return value

Final return value ................................


[6]

© UCLES 2018 9608/41/O/N/18


13

(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]

(ii) Rewrite the Calculate() function in pseudocode, using an iterative algorithm.

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

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

© UCLES 2018 9608/41/O/N/18 [Turn over


14

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").

The game is written using object-oriented programming.

The class, Cards, has the private properties:

• Number
• Shape

and the methods:

• 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.

(a) Explain why the properties are private.

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

.............................................................................................................................................. [2]

© UCLES 2018 9608/41/O/N/18


15

(b) Write program code for the Constructor() method.

Programming language ............................................................................................................

Program code

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

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

(c) Write program code for the GetNumber() method.

Programming language ............................................................................................................

Program code

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

.............................................................................................................................................. [2]

(d) A card, OneS, has the value 1 for Number and the value "square" for Shape.

Write program code to instantiate an instance of Cards for OneS.

Programming language ............................................................................................................

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.

Write program code for the Compare() function.

Programming language ............................................................................................................

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.

© UCLES 2018 9608/41/O/N/18


9608/41 Cambridge International AS/A Level – Mark Scheme October/November 2018
PUBLISHED
Question Answer Marks

1(a)(i) 1 mark for each correct statement: 2

• bird(lays_egg).
• bird(has_wings).

1(a)(ii) 1 mark for each correct line: 2

• feature(eagle, lays_eggs).
• feature(eagle, has_wings).

1(b)(i) 1 mark for each animal: 2

tuna, crab

1(b)(ii) 1 mark per bullet point: 2

• feature()
• tuna, C

feature(tuna, C)

1(c) 1 mark per bullet point to max 3: 3

• feature(X,Y) AND bird(Y) // feature(X, has_wings)


• AND
• feature(X,Z) AND bird(Z) // feature(X, lays_eggs)

(feature(X, Y) AND bird(Y)) AND (feature(X, Z) AND bird(Z))

1(d)(i) A programming style/classification // characteristics/features that programming language has/uses 1

1(d)(ii) 1 mark for each: 2

• Low-level
• Imperative // Procedural

© UCLES 2018 Page 4 of 18


9608/41 Cambridge International AS/A Level – Mark Scheme October/November 2018
PUBLISHED
Question Answer Marks

2(a) 1 mark per bullet point to max 4: 4

• declaration of type Book


• Title, Author and ISBN as String
• Fiction as Boolean
• LastRead as Date

For example:

TYPE Book
DECLARE Title : String
DECLARE Author : String
DECLARE ISBN : String
DECLARE Fiction : Boolean
DECLARE LastRead : Date
ENDTYPE

© UCLES 2018 Page 5 of 18


9608/41 Cambridge International AS/A Level – Mark Scheme October/November 2018
PUBLISHED
Question Answer Marks

2(b) 1 mark per bullet point to max 4: 4

• 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:

Function Hash (ISBN As String) As Integer


ISBNint = convert.toInt32(ISBN)
Hash = (ISBNint MOD 2000) + 1
End Function

Pascal:

function Hash(ISBN : String) : Integer


begin
ISBNint = StrToInt(ISBN)
Hash = (ISBNint MOD 2000) + 1
end;

© UCLES 2018 Page 6 of 18


9608/41 Cambridge International AS/A Level – Mark Scheme October/November 2018
PUBLISHED
Question Answer Marks

2(c) 1 mark per bullet point to max 8: 8

• Procedure FindBook declaration and prompt and input ISBN


• Validate data input has 13 characters
• « and are all numeric
• ..loop until valid
• Call Hash() with input data and store return data
• Open MyBooks.dat for reading as random file and close
• Finding the record using return value Hash()
• Get the data for the record
• «store in variable of type Book
• «output all the data for the record

© UCLES 2018 Page 7 of 18


9608/41 Cambridge International AS/A Level – Mark Scheme October/November 2018
PUBLISHED
Question Answer Marks

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

© UCLES 2018 Page 8 of 18


9608/41 Cambridge International AS/A Level – Mark Scheme October/November 2018
PUBLISHED
Question Answer Marks

3(a) • LIFO / last in first out 1

3(b)(i) Points to the next free space on the stack 1

3(b)(ii) 1 mark per bullet to max 3 2

• Correct stack contents


• StackPointer = 4

StackPointer 4 StackContents

0 "Screw 1"

1 "Screw 2"

2 "Back case"

3 "Light 1"

© UCLES 2018 Page 9 of 18


9608/41 Cambridge International AS/A Level – Mark Scheme October/November 2018
PUBLISHED
Question Answer Marks

3(c)(i) 1 mark for each correct statement: 5

PROCEDURE POP
IF StackPointer = 0
THEN
OUTPUT ("The stack is empty")
ELSE
StackPointer ← StackPointer - 1
OUTPUT Parts[StackPointer]
Parts(StackPointer) ← "*"
ENDIF
ENDPROCEDURE

3(c)(ii) 1 mark for each completed statement: 4

PROCEDURE PUSH (BYVALUE Value : String)


IF StackPointer > 19
THEN
OUTPUT "Stack full"
ELSE
Parts[StackPointer] ← Value
StackPointer ← StackPointer + 1
ENDIF
ENDPROCEDURE

© UCLES 2018 Page 10 of 18


9608/41 Cambridge International AS/A Level – Mark Scheme October/November 2018
PUBLISHED
Question Answer Marks

4(a)(i) A function/subroutine defined in terms of itself // a function/subroutine that calls itself 1

4(a)(ii) 06 1

4(b) 1 mark for each bullet point: 6

• –60 as final return value


• 3*2*1*–10

1 mark for each row in table

Call Number Function call Number = 0 ? Return value

1 Calculate(3) False 3*Calculate(2)

2 Calculate(2) False 2*Calculate(1)

3 Calculate(1) False 1*Calculate(0)

4 Calculate(0) TRUE –10

4(c)(i) 1 mark per bullet point: 2

• 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

© UCLES 2018 Page 11 of 18


9608/41 Cambridge International AS/A Level – Mark Scheme October/November 2018
PUBLISHED
Question Answer Marks

4(c)(ii) 1 mark per bullet point to max 5: 5

• Function header with parameter and Returning calculated value


• Loop parameter times (up to number, or down from number)«
• «Multiplying by loop counter
• Multiplying by –10
• Dealing with starting value correctly

For example:

FUNCTION Calculate(Number : INTEGER) RETURNS INTEGER


DECLARE Count : INTEGER
DECLARE Value : INTEGER
Value ← −10
FOR Count ← 1 to Number
Value ← Value * Count
ENDFOR

RETURN Value
ENDFUNCTION

Question Answer Marks

5(a) 1 mark per bullet point to max 2: 2

• 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

© UCLES 2018 Page 12 of 18


9608/41 Cambridge International AS/A Level – Mark Scheme October/November 2018
PUBLISHED
Question Answer Marks

5(b) 1 mark per bullet point: 5

• 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)

© UCLES 2018 Page 13 of 18


9608/41 Cambridge International AS/A Level – Mark Scheme October/November 2018
PUBLISHED
Question Answer Marks

5(b) Examples:

Python

def __init__(self, Num, theShape):


if (Num >= 0 and Num <= 9) and (theShape = "square" or theShape = "triangle" or
theShape = "circle”) :
self. __Number = Num
self.__Shape = TheShape
else
print("Error")
endif

VB.NET

Public Sub New(Num As Integer, theShape As String)


IF (Num >= 0 and Num <= 9) and (theShape = "square" or theShape = "triangle" or
theShape = "circle") THEN
Number = Num
Shape = theShape
ELSE
Console.WriteLine("Error")
ENDIF
End Sub

Pascal

constructor Cards.Create(Num : Integer, theShape : String);


begin
If (Num >= 0 and Num <= 9) and (theShape = "square" or theShape = "triangle" or theShape =
"circle")
Number := Num;
Shape := theShape;
Else
Writeln("Error") ;
end;

© UCLES 2018 Page 14 of 18


9608/41 Cambridge International AS/A Level – Mark Scheme October/November 2018
PUBLISHED
Question Answer Marks

5(c) 1 mark per bullet point to max 2: 2

• Function declaration for GetNumber


• Returning Number

Examples:

Python

def GetNumber():
return(self.__Number)

VB.NET

Public Function GetNumber() As Integer


Return(Number)
End Function

Pascal

function Cards.GetNumber() : Integer;


begin
GetNumber := Number;
end;

© UCLES 2018 Page 15 of 18


9608/41 Cambridge International AS/A Level – Mark Scheme October/November 2018
PUBLISHED
Question Answer Marks

5(d) 1 mark per bullet point to max 2: 2

• Assigning to OneS and correct instantiation


• Correct parameter values

Examples:

Python

OneS = Cards(1, "square")

VB.NET

Dim OneS As New Cards(1, "square")


or
Dim OneS As Cards = New Cards(1, "square")
or
OneS = New Cards(1, "square")

Pascal

var OneS : Cards;


OneS := Cards.Create(1, "square")

5(e) 1 mark per bullet point: 6

• function declaration (returning integer) and taking 2 cards as parameter


• comparison of Number and Shape «
• « if the same output ‘SNAP’ and return –1
• Compare Number of each to find highest and return the highest number
• return either number if the same
• correct use of .GetNumber() and .GetShape()throughout

© UCLES 2018 Page 16 of 18


9608/41 Cambridge International AS/A Level – Mark Scheme October/November 2018
PUBLISHED
Question Answer Marks

5(e) Examples:

Python

def Compare(P1Card, P2Card):


if P1Card.GetNumber() = P2Card.GetNumber() AND
P1Card.GetShape() = P2Card.GetShape():
Print("SNAP")
return -1
elif P2Card.GetNumber() > P1Card.GetNumber():
return P2Card.GetNumber()
else:
return P1Card.GetNumber()

VB.NET

Function Compare(P1Card As Cards, P2Card As Cards) As Integer


IF P1Card.GetNumber() = P2Card.GetNumber()AND
P1Card.GetShape() = P2Card.GetShape()THEN

Console.writeline("SNAP")
Return -1
ELSEIF P2Card.GetNumber() > P1Card.GetNumber() THEN
P2Card.GetNumber()
ELSE
Return P1Card.GetNumber()
ENDIF
End Function

© UCLES 2018 Page 17 of 18


9608/41 Cambridge International AS/A Level – Mark Scheme October/November 2018
PUBLISHED
Question Answer Marks

5(e) Pascal

function Compare(P1Card : Cards, P2Card : Cards) : Integer;


begin
if P1Card.GetNumber() = P2Card.GetNumber()AND
P1Card.GetShape() = P2Card.GetShape() then
writeline("SNAP");
return −1;
else if P2Card.GetNumber() > P1Card.GetNumber() then
return P2Card.GetNumber();
else
return P1Card.GetNumber();
end;

© UCLES 2018 Page 18 of 18


Cambridge Assessment International Education
Cambridge International Advanced Subsidiary and Advanced Level

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills May/June 2019
PRE-RELEASE MATERIAL
* 9 1 7 8 5 9 5 1 7 0 *

No Additional Materials are required.


This material should be given to the relevant teachers and candidates as soon as it has been received
at the centre.

READ THESE INSTRUCTIONS FIRST

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.

This document consists of 6 printed pages and 2 blank pages.

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

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.

Questions on the examination paper may ask the candidate to write:

• structured English
• pseudocode
• program code

A program flowchart should be considered as an alternative to pseudocode for documenting a


high-level algorithm design.

Candidates should be confident with:

• the presentation of an algorithm using either a program flowchart or pseudocode


• the production of a program flowchart from given pseudocode and vice versa

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.

DECLARE <identifier> : <data type>

If Python is the chosen language, each variable’s identifier (name) and its intended data type must be
documented using a comment statement.

Structured English – Variables

An algorithm in pseudocode uses variables, which should be declared. An algorithm in structured


English does not always use variables. In this case, the candidate needs to use the information given
in the question to complete an identifier table. The table needs to contain an identifier, data type and
description for each variable.

© UCLES 2019 9608/41/PRE/M/J/19


3

TASK 1 - Binary trees and linked lists

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

Left child node 15 26 Right child node

Add the data 10, 34 and 22 to the binary tree.

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

Left pointer 21 Right pointer

15 26

© UCLES 2019 9608/41/PRE/M/J/19 [Turn over


4

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

Left pointer 21 Right pointer

∅ 15 ∅ ∅ 26 ∅

If we add three more items to the tree, it becomes:

Root pointer

Left pointer 21 Right 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.

© UCLES 2019 9608/41/PRE/M/J/19


5

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:

RootPointer LeftPointer Data RightPointer

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:

RootPointer LeftPointer Data RightPointer


0 1 21 2
0
1 3 15 ∅
2 4 26 5
3 ∅ 4 ∅
FreePointer 4 ∅ 24 ∅

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

Research how an item of data is added to a linked list.

Create a program in the language of your choice that adds an item of data to a list.

© UCLES 2019 9608/41/PRE/M/J/19 [Turn over


6

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:

• PUSH, which adds an item to the collection


• POP, which removes the item that the program most recently added unless the stack is already
empty.

TASK 2.1

The values 21, 15 and 26 are currently stored in a stack as follows:

26

15

21

The following commands are carried out.

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.

© UCLES 2019 9608/41/PRE/M/J/19


Cambridge Assessment International Education
Cambridge International Advanced Subsidiary and Advanced Level
* 4 6 5 8 9 5 0 5 8 1 *

COMPUTER SCIENCE 9608/41


Paper 4 Further Problem-solving and Programming Skills May/June 2019
2 hours
Candidates answer on the Question Paper.
No Additional Materials are required.
No calculators allowed.

READ THESE INSTRUCTIONS FIRST

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.

Answer all questions.


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.

The maximum number of marks is 75.

This document consists of 18 printed pages and 2 blank pages.

DC (PQ) 180360
© UCLES 2019 [Turn over
2

1 (a) A stack contains the values 'red', 'blue', 'green' and 'yellow'.

yellow Top of stack


green
blue
red

(i) Show the contents of the stack in part(a) after the following operations.

POP()

PUSH('purple')

PUSH('orange')

[1]

© UCLES 2019 9608/41/M/J/19


3

(ii) Show the contents of the stack from part(a)(i) after these further operations.

POP()

POP()

PUSH('brown')

POP()

PUSH('black')

[1]

(b) A queue is an alternative Abstract Data Type (ADT).

Describe a queue.

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

............................................................................................................................................. [3]

© UCLES 2019 9608/41/M/J/19 [Turn over


4

2 A computer games club wants to run a competition. The club needs a system to store the scores
achieved in the competition.

A selection of score data is as follows:

99, 125, 121, 97, 109, 95, 135, 149

(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).

RootPointer Index LeftPointer Data RightPointer

0 0 99

1 125

2 121

3 97
FreePointer
4 109

5 95

6 135

7 149

[6]

© UCLES 2019 9608/41/M/J/19 [Turn over


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.

Complete the six missing sections in the algorithm.

FUNCTION FindElement(Item : INTEGER) RETURNS …………………………………………

…………………………………………… ← RootPointer

WHILE CurrentPointer …………………………………………… NullPointer

IF List[CurrentPointer].Data <> ……………………………………………

THEN

CurrentPointer ← List[……………………………………………].Pointer

ELSE

RETURN CurrentPointer

ENDIF

ENDWHILE

CurrentPointer ← NullPointer

………………………………………… CurrentPointer

ENDFUNCTION

[6]

© UCLES 2019 9608/41/M/J/19


7

(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.

(i) Imperative ..........................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

..................................................................................................................................... [3]

(ii) Object-oriented ..................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

..................................................................................................................................... [3]

© UCLES 2019 9608/41/M/J/19 [Turn over


8

(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

Create() // method to create and initialise an object using


// language-appropriate constructor
SetScore() // checks that the Score parameter has a valid value
// if so, assigns it to Score
SetCategory() // sets Category based on player’s Score
SetPlayerID() // allows a player to change their PlayerID
// validates the new PlayerID
GetScore() // returns Score
GetCategory() // returns Category
GetPlayerID() // returns PlayerID

© UCLES 2019 9608/41/M/J/19


9

(i) The constructor receives the parameter InputPlayerID to create the PlayerID.
Other properties are initialised as instructed in the class diagram.

Write program code for the Create() constructor method.

Programming language .....................................................................................................

Program code

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

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

© UCLES 2019 9608/41/M/J/19 [Turn over


10

(ii) Write program code for the following three get methods.

Programming language .....................................................................................................

GetScore()

Program code

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

GetCategory()

Program code

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

GetPlayerID()

Program code

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................
[4]

© UCLES 2019 9608/41/M/J/19


11

(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.

Use suitable input and output messages.

Write program code for SetPlayerID().

Programming language .....................................................................................................

Program code

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

..................................................................................................................................... [4]

© UCLES 2019 9608/41/M/J/19 [Turn over


12

(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.

Write program code for SetScore(ScoreInput : INTEGER).

Programming language .....................................................................................................

Program code

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

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

© UCLES 2019 9608/41/M/J/19


13

(v) Write program code for the method SetCategory(). Use the properties and methods
in the original class definition.

Players will be placed in one of the following categories.

Category Criteria

Advanced Score is greater than 120


Intermediate Score is greater than 80 and less than or equal to 120
Beginner Score is greater than or equal to 50 and less than or equal to 80
Not Qualified Score is less than 50

Programming language .....................................................................................................

Program code

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

..................................................................................................................................... [4]

© UCLES 2019 9608/41/M/J/19 [Turn over


14

(vi) Joanne has played the first game to place her in a category for the competition.

The procedure CreatePlayer()performs the following tasks.

• allows the player ID and score to be input with suitable prompts


• creates an instance of Player with the identifier JoannePlayer
• sets the score for the object
• sets the category for the object
• outputs the category for the object

Write program code for the CreatePlayer()procedure.

Programming language .....................................................................................................

Program code

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

..................................................................................................................................... [8]

© UCLES 2019 9608/41/M/J/19


15

(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

Advanced Score is greater than 120


Intermediate Score is greater than 80 and less than or equal to 120
Beginner Score is greater than or equal to 50 and less than or equal to 80
Not Qualified Score is less than 50

Complete the table to provide test data for each category.

Category Type of test data Example test data


Normal

Beginner Abnormal

Boundary

Normal

Intermediate Abnormal

Boundary

Normal

Advanced Abnormal

Boundary
[3]

© UCLES 2019 9608/41/M/J/19 [Turn over


16

(f) In part (b), the club stored scores in a 1D array. This allows the club to sort the scores.

The following is a sorting algorithm in pseudocode.

NumberOfScores ← 5

FOR Item ← 1 TO NumberOfScores – 1

InsertScore ← ArrayData[Item]

Index ← Item – 1

WHILE (ArrayData[Index] > InsertScore) AND (Index >= 0)

ArrayData[Index + 1] ← ArrayData[Index]

Index ← Index – 1

ENDWHILE

ArrayData[Index + 1] ← InsertScore

ENDFOR

(i) Give the name of this algorithm.

..................................................................................................................................... [1]

(ii) State the name of one other sorting algorithm.

..................................................................................................................................... [1]

© UCLES 2019 9608/41/M/J/19


17

(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]

© UCLES 2019 9608/41/M/J/19 [Turn over


18

3 Some algorithms can be written using recursion.

(a) State two features of recursion.

Feature 1 ...................................................................................................................................

Feature 2 ...................................................................................................................................
[2]

(b) Explain what a compiler has to do to implement recursion.

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

...................................................................................................................................................

............................................................................................................................................. [3]

© UCLES 2019 9608/41/M/J/19


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2019
PUBLISHED

Question Answer Marks

1(a)(i) 1 mark for correct stack 1

orange

purple

green

blue

red

1(a)(ii) 1 mark for correct stack 1

black

green

blue

red

1(b) 1 mark per bullet point to max 3 3


• (Linear) data structure
• First in First out // FIFO // An item is added to the end of the queue and an item
is removed from the front
• All items are kept in the order they are entered
• It has a head pointer and a tail pointer
• Can be static or dynamic
• A queue can be circular «
• «when the (tail) pointer reaches the last position it returns to the first

© UCLES 2019 Page 3 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2019
PUBLISHED

Question Answer Marks

2(a)(i) 1 mark per bullet point 5


• 95 to left of 97
• 109 to left of 121
• 135 to right of 125
• 149 to right of 135
• Null points in all places and no inappropriate pointers

RootPointer

LeftPointer RightPointer

99

97 Ø 125

Ø 95 Ø 121 Ø Ø 135

Ø 109 Ø Ø 149 Ø

© UCLES 2019 Page 4 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2019
PUBLISHED

Question Answer Marks

2(a)(ii) 1 mark per bullet point 6

• FreePointer as 8
• 99
• 125
• 121 and 97
• 109 and 95
• 135 and 149

RootPointer Index LeftPointer Data RightPointer

0 [0] 3 99 1

[1] 2 125 6

FreePointer [2] 4 121 null

8 [3] 5 97 null

[4] null 109 null

[5] null 95 null

[6] null 135 7

[7] null 149 null

[8]

2(b) 1 mark for each completed section 6

FUNCTION FindElement(Item : INTEGER) RETURNS INTEGER


CurrentPointer ← RootPointer
WHILE CurrentPointer <> NullPointer
IF List[CurrentPointer].Data <> Item
THEN
CurrentPointer ← List[CurrentPointer].Pointer
ELSE
RETURN CurrentPointer
ENDIF
ENDWHILE
CurrentPointer ← NullPointer
RETURN CurrentPointer
ENDFUNCTION

2(c)(i) 1 mark per bullet point to max 3 3


e.g.
• A sequence of steps that change the state of the program
• The steps are in the order they should be carried out
• e.g. procedural programming/language
• Groups code into self-contained blocks // split the program into modules
• « which are subroutines // by example

© UCLES 2019 Page 5 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2019
PUBLISHED

Question Answer Marks

2(c)(ii) 1 mark per bullet point to max 3 3


e.g.
• Creates classes
• «as a blueprint for an object // objects are instances of classes
• «that have properties/attributes and methods
• « that can be private to the class // properties can only be accessed by the
class's methods // encapsulation
• Subclasses can inherit from superclasses (child and parent)
• A subclass can inherit the methods and properties from the superclass
• A subclass can change the methods from the superclass // subclass can use
polymorphism
• Objects can interact with each other

2(d)(i) 1 mark per bullet point 5

• Method header and close (where appropriate)


• «with InputPlayerID parameter
• Initialise Score to 0
• Initialise Category to "Not Qualified"
• Initialise PlayerID to parameter

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

© UCLES 2019 Page 6 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2019
PUBLISHED

Question Answer Marks

2(d)(ii) 1 mark per bullet point 4

• 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

© UCLES 2019 Page 7 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2019
PUBLISHED

Question Answer Marks

2(d)(iii) 1 mark per bullet point 4

• Set method header and close (where appropriate)


• Input value
• Looping until input value is correct length «
• « storing valid input value in PlayerID

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

© UCLES 2019 Page 8 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2019
PUBLISHED

Question Answer Marks

2(d)(iv) 1 mark per bullet point 5

• Function header and close (where appropriate) and takes ScoreInput as


parameter
• Check if 0 <= ScoreInput <= 150
• «if valid, set Score to parameter
• «if not valid, output error
• Returns TRUE if valid and returns FALSE if not valid

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

© UCLES 2019 Page 9 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2019
PUBLISHED

Question Answer Marks

2(d)(v) 1 mark per bullet point 4

• Procedure header and close (where appropriate)


• Accessing Score attribute
• Correct selection to assign each category
• « storing in Category attribute

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

© UCLES 2019 Page 10 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2019
PUBLISHED

Question Answer Marks

2(d)(vi) 1 mark per bullet point 8

• CreatePlayer() header and close (where appropriate)


• Input of score and PlayerID with suitable prompts
• Create instance of Player named JoannePlayer «
• «with PlayerID as parameter
• Call method SetScore for JoannePlayer with parameter Score
• «storing return value
• «outputting appropriate message for not valid
• Call SetCategory for JoannePlayer
• Output Category for JoannePlayer «
• « using GetCategory for object Joanne

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;

© UCLES 2019 Page 11 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2019
PUBLISHED

Question Answer Marks

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()

Dim JoannePlayer As New Player(InputPlayerID)


if JoannePlayer.SetScore(Score) = True then
JoannePlayer.SetCategory()
Console.WriteLine(JoannePlayer.GetCategory())
else
Console.Writeline("Invalid score")
endif
End Sub

2(e) 1 mark per bullet point 3

• 3 correct Normal test data


• 3 correct Abnormal test data
• 3 correct Boundary test data

Category Type of test data Example test data

Beginner Normal e.g. 75

Abnormal e.g. 85 / bob

Boundary 80, 50

Intermediate Normal e.g. 95

Abnormal e.g. 70 / bob

Boundary 81, 120

Advanced Normal e.g. 125

Abnormal e.g. 115 / bob

Boundary 121, 150

2(f)(i) Insertion sort 1

2(f)(ii) One from: 1


• Bubble sort
• Merge sort

© UCLES 2019 Page 12 of 13


9608/41 Cambridge International AS/A Level – Mark Scheme May/June 2019
PUBLISHED

Question Answer Marks

2(f)(iii) 1 mark per shaded section 7

ArrayData
Item NumberOfScores InsertScore Index
0 1 2 3 4

99 125 121 109 115

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

Question Answer Marks

3(a) 1 mark per bullet point to max 2 2

• It is defined in terms of itself // it calls itself


• It has a stopping condition // base case
• It is a self-contained subroutine
• It can return data to its previous call

3(b) 1 mark per bullet point to max 3 3

• (When the recursive call is made) all values/data are put on «


• « the stack
• When the stopping condition/base case is met
• «the algorithm unwinds
• «the last set of values are taken off the stack (in reverse order)

© UCLES 2019 Page 13 of 13

S-ar putea să vă placă și