Skip to content

20.1 Programming Paradigms

A Level · 57 questions found

  • What a programming paradigm is
  • Low-level: addressing modes (immediate, direct, indirect, indexed, relative)
  • Imperative/Procedural: variables, constructs, procedures, functions
  • OOP: objects, attributes, methods, classes, inheritance, polymorphism, encapsulation, getters/setters, instances
  • Design appropriate classes; write OOP code demonstrating these concepts
  • Declarative: write facts and rules; satisfy a goal using logic
Q2
Oct/Nov 2025 Paper 4 v1

A program stores data about trains and train stations using Object-Oriented Programming (OOP).

The class Train stores the data about the trains:
Train Train
TrainIDNumber : String
Route : Integer
stores the train ID number
stores the route number the train is travelling

Constructor()
GetTrainIDNumber()
GetRoute()
initialisesTrainIDNumber andRoute to the parameter
values
returns the train ID number
returns the route number the train is travelling

(a) (i) Write program code to declare the class Train and its constructor. 4 marks

Do not declare the other methods.

All attributes should be private.

Use your programming language appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program as Question2_N25 .

Copy and paste the program code into part 2(a)(i) in the evidence document.

(ii) The methods GetTrainIDNumber() and GetRoute() return the appropriate attribute. 3 marks

Write program code for GetTrainIDNumber() and GetRoute()

Save your program.

Copy and paste the program code into part 2(a)(ii) in the evidence document.

(b) The program is tested with four trains: 2 marks

train ID number route
12ADV 134
33ART 20
9FKF 3
21VBC 24

Write program code to declare an instance of Train for each of the four trains.

Save your program.

Copy and paste the program code into part 2(b) in the evidence document.

(c) The class Station stores the data about the stations:
Station Station
StationID : String
NumberPlatforms : Integer
Trains[0:9] : Train
NumberTrains : Integer
stores the station ID
stores the number of platforms at the station
stores the trains currently at the station platforms
stores the number of trains currently at the station
platforms
Constructor()
GetTrains()
AddTrain()
initialisesStationID andNumberPlatforms
to the parameter values, initialisesTrains to an
empty array andNumberTrains to0
returns a string containing data about the trains
currently at the station platforms
takes aTrain parameter and stores it if there is a
platform available; each platform can only have one
train

(i) Write program code to declare the class Station and its constructor. 3 marks

Do not declare the other methods.

All attributes should be private.

Use your programming language appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program.

Copy and paste the program code into part 2(c)(i) in the evidence document.

(ii) The method AddTrain() takes a Train parameter. The method compares the attributes NumberTrains and NumberPlatforms to identify if there is a platform available (a platform currently with no train). 4 marks

The method returns FALSE if there are no platforms available.

If there is a platform available, the method:

  • stores the Train parameter in the array Trains

  • updates the appropriate attribute(s)

  • returns TRUE

Write program code for AddTrain()

Save your program.

Copy and paste the program code into part 2(c)(ii) in the evidence document.

(iii) The method GetTrains() returns the string "There are no trains" if there are no trains at the station platforms. 6 marks

If there are trains at the station platforms, the method returns a string in the format:

        The trains at station <StationID> are:
        <TrainIDNumber> on route number <Route>

The line <TrainIDNumber> on route number <Route> is repeated for each train at the station platforms.

For example: If the station with the station ID "NT1" has two trains with the train ID numbers "48RTG", "6UFH", the method will produce this output:

        The trains at station NT1 are:
        48RTG on route number 43
        6UFH on route number 12

Write program code for GetTrains()

Save your program.

Copy and paste the program code into part 2(c)(iii) in the evidence document.

The program is tested with two
station ID number of
platforms
STH 2
NTH 1

(i) Write program code to amend the main program to declare an instance of Station for each of the two stations. 2 marks

Save your program.

Copy and paste the program code into part 2(d)(i) in the evidence document.

(ii) The four trains attempt to stop at the following stations in the order given: 4 marks

  • Train 12ADV, station STH

  • Train 33ART, station STH

  • Train 9FKF, station STH

  • Train 21VBC, station NTH

Write program code to amend the main program to:

  • add each train to the given station using AddTrain()

  • output "Station is full" for any train where the return value indicates it cannot be added to the station

  • output the trains at each station using GetTrains()

Save your program.

Copy and paste the program code into part 2(d)(ii) in the evidence document.

(iii) Test your program. 2 marks

Take a screenshot of the output(s).

Save your program.

Copy and paste the screenshot(s) into part 2(d)(iii) in the evidence document.

A program stores data about trains and train stations using Object-Oriented Programming (OOP). |The class Train stores the data about the trains:|| |---|---| |**`Train`**|**`Train`**| |`TrainIDNumber : String`<br>`Route : Integer`|stores the train ID number<br>stores the route number the train is travelling| |<br>`Constructor()`<br>`GetTrainIDNumber()`<br>`GetRoute()`|initialises`TrainIDNumber` and`Route` to the parameter<br>values<br>returns the train ID number<br>returns the route number the train is travelling| **(a) (i)** Write program code to declare the class `Train` and its constructor. <span class="part-marks">4 marks</span> Do **not** declare the other methods. All attributes should be private. Use your programming language appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program as **Question2_N25** . Copy and paste the program code into part **2(a)(i)** in the evidence document. #### (ii) The methods `GetTrainIDNumber()` and `GetRoute()` return the appropriate attribute. <span class="part-marks">3 marks</span> Write program code for `GetTrainIDNumber()` and `GetRoute()` Save your program. Copy and paste the program code into part **2(a)(ii)** in the evidence document. ### (b) The program is tested with four trains: <span class="part-marks">2 marks</span> |train ID number|route| |---|---| |12ADV|134| |33ART|20| |9FKF|3| |21VBC|24| Write program code to declare an instance of `Train` for each of the **four** trains. Save your program. Copy and paste the program code into part **2(b)** in the evidence document. |(c) The class Station stores the data about the stations:|| |---|---| |**`Station`**|**`Station`**| |`StationID : String`<br>`NumberPlatforms : Integer`<br>`Trains[0:9] : Train`<br>`NumberTrains : Integer`|stores the station ID<br>stores the number of platforms at the station<br>stores the trains currently at the station platforms<br>stores the number of trains currently at the station<br>platforms| |`Constructor()`<br>`GetTrains()`<br>`AddTrain()`|initialises`StationID` and`NumberPlatforms` <br>to the parameter values, initialises`Trains` to an<br>empty array and`NumberTrains` to`0`<br>returns a string containing data about the trains<br>currently at the station platforms<br>takes a`Train` parameter and stores it if there is a<br>platform available; each platform can only have one<br>train| #### (i) Write program code to declare the class `Station` and its constructor. <span class="part-marks">3 marks</span> Do **not** declare the other methods. All attributes should be private. Use your programming language appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into part **2(c)(i)** in the evidence document. #### (ii) The method `AddTrain()` takes a `Train` parameter. The method compares the attributes `NumberTrains` and `NumberPlatforms` to identify if there is a platform available (a platform currently with no train). <span class="part-marks">4 marks</span> The method returns `FALSE` if there are no platforms available. If there is a platform available, the method: - stores the `Train` parameter in the array `Trains` - updates the appropriate attribute(s) - returns `TRUE` Write program code for `AddTrain()` Save your program. Copy and paste the program code into part **2(c)(ii)** in the evidence document. #### (iii) The method `GetTrains()` returns the string `"There are no trains"` if there are no trains at the station platforms. <span class="part-marks">6 marks</span> If there are trains at the station platforms, the method returns a string in the format: ``` The trains at station <StationID> are: <TrainIDNumber> on route number <Route> ``` The line `<TrainIDNumber> on route number <Route>` is repeated for each train at the station platforms. For example: If the station with the station ID `"NT1"` has two trains with the train ID numbers `"48RTG"`, `"6UFH"`, the method will produce this output: ``` The trains at station NT1 are: 48RTG on route number 43 6UFH on route number 12 ``` Write program code for `GetTrains()` Save your program. Copy and paste the program code into part **2(c)(iii)** in the evidence document. |The program is|tested with two| |---|---| |**station ID**|**number of**<br>**platforms**| |STH|2| |NTH|1| #### (i) Write program code to amend the main program to declare an instance of `Station` for each of the **two** stations. <span class="part-marks">2 marks</span> Save your program. Copy and paste the program code into part **2(d)(i)** in the evidence document. #### (ii) The four trains attempt to stop at the following stations in the order given: <span class="part-marks">4 marks</span> - Train 12ADV, station STH - Train 33ART, station STH - Train 9FKF, station STH - Train 21VBC, station NTH Write program code to amend the main program to: - add each train to the given station using `AddTrain()` - output `"Station is full"` for any train where the return value indicates it cannot be added to the station - output the trains at each station using `GetTrains()` Save your program. Copy and paste the program code into part **2(d)(ii)** in the evidence document. #### (iii) Test your program. <span class="part-marks">2 marks</span> Take a screenshot of the output(s). Save your program. Copy and paste the screenshot(s) into part **2(d)(iii)** in the evidence document.
Show mark scheme

2(a)(i) [4 marks]

1 mark each • Class header (and end) • Declaration of 2 private attributes with correct data types • Constructor header (and end) within class with 2 parameters … • … assigning parameters to attributes Example program code Java class Train{ private String Number; private Integer Route; public Train(String pNumber, Integer pRoute){ Number = pNumber; Route = pRoute; }} VB.NET Class Train Private TrainIDNumber As String Private Route As Integer Sub New(pNumber, pRoute) TrainIDNumber = pNumber Route = pRoute End Sub End Class Python class Train(): def init(self, pNumber, pRoute): self.__TrainIDNumber = pNumber #string self.__Route = pRoute #integer

2(a)(ii) [3 marks]

1 mark each • One get method header (and end) with no parameter … • … returning correct attribute • Second correct get method Example program code Java public String GetTrainNumber(){ return Number; } public Integer GetRoute(){ return Route; } VB.NET Function GetTrainIDNumber() Return TrainIDNumber End Function Function GetRoute() Return Route End Function Python def GetTrainIDNumber(self): return self.__TrainIDNumber def GetRoute(self): return self.__Route

2(b) [2 marks]

1 mark each • One instance of train with correct arguments and stored in a variable/structure • Remaining three instances correct Example program code Java Train FirstTrain = new Train("12ADV", 134); Train SecondTrain = new Train("33ART", 20); Train ThirdTrain = new Train("9FKF", 3); Train FourthTrain = new Train("21VBC", 24) VB.NET Dim FirstTrain As Train = New Train("12ADV", 134) Dim SecondTrain As Train = New Train("33ART", 20) Dim ThirdTrain As Train = New Train("9FKF", 3) Dim FourthTrain As Train = New Train("21VBC", 24) Python FirstTrain = Train("12ADV",134) SecondTrain = Train("33ART",20) ThirdTrain = Train("9FKF",3) FourthTrain = Train("21VBC",24)

2(c)(i)

Python class Station(): def init(self, pID, pNumberOfPlatforms): self.__StationID = pID #string self.__NumberPlatforms = pNumberOfPlatforms #integer self.__Trains = [] #train 10 elements self.__NumberTrains = 0 #integer

2(c)(ii) [4 marks]

1 mark each • Method header (and close) taking one parameter Train • Checking if all platforms are full and returning FALSE • (Otherwise) Storing parameter in array … Trains • … incrementing and returning NumberTrains True Example program code Java public Boolean AddTrain(Train NewTrain){ if(NumberTrains >= NumberPlatforms){ return false; } Trains[NumberTrains] = NewTrain; NumberTrains++; return true; } VB.NET Function AddTrain(NewTrain) If NumberTrains >= NumberPlatforms Then Return False End If Trains(NumberTrains) = NewTrain NumberTrains = NumberTrains + 1 Return True End Function Python def AddTrain(self, NewTrain): if self.__NumberTrains >= self.__NumberPlatforms: return False else: self.__Trains.append(NewTrain) self.__NumberTrains += 1 return True

2(c)(iii)

Python def GetTrains(self): if self.__NumberTrains == 0: return "There are no trains" OutputLine = "The trains at station " + self.__StationID + " are: \n" for x in range(self.__NumberTrains): OutputLine = OutputLine + self.__Trains[x]. GetTrainIDNumber() + " on route number " + str(self.__Trains[x].GetRoute()) + "\n" return OutputLine

2(d)(i) [2 marks]

1 mark each • One instance of created with correct arguments and stored Station • Second correct instance and stored Example program code Java Station SouthStation = new Station("STH", 2); Station NorthStation = new Station("NTH", 1); VB.NET Dim SouthStation As Station = New Station("STH", 2) Dim NorthStation As Station = New Station("NTH", 1) Python SouthStation = Station("STH",2) NorthStation = Station("NTH",1)

2(d)(ii)

Console.WriteLine("Station is full") End If ReturnValue = SouthStation.AddTrain(ThirdTrain) If ReturnValue = False Then Console.WriteLine("Station is full") End If ReturnValue = NorthStation.AddTrain(FourthTrain) If ReturnValue = False Then Console.WriteLine("Station is full") End If Console.WriteLine(SouthStation.GetTrains()) Console.WriteLine(NorthStation.GetTrains()) Python ReturnValue = SouthStation.AddTrain(FirstTrain) if ReturnValue == False: print("Station is full") ReturnValue = SouthStation.AddTrain(SecondTrain) if ReturnValue == False: print("Station is full") ReturnValue = SouthStation.AddTrain(ThirdTrain) if ReturnValue == False: print("Station is full") ReturnValue = NorthStation.AddTrain(FourthTrain) if ReturnValue == False: print("Station is full") print(SouthStation.GetTrains()) print(NorthStation.GetTrains())

2(d)(iii) [2 marks]

1 mark each, screenshot(s) showing: • One output of "Station is full" • Output of correct data for both stations (in correct format) e.g.

Q1
Oct/Nov 2025 Paper 4 v2

A program stores data about birds using Object-Oriented Programming (OOP).

The class Bird stores the data about the birds: Bird
Bird Bird
DistancePerHour : Real
Species : String
XPosition : Real
YPosition : Real
stores the number of kilometres per hour (km/h) the bird
can fly (between 0.0 and 100.0 inclusive)
stores the species of the bird, for example Pigeon
stores the current horizontal position of the bird
stores the current vertical position of the bird
Constructor()
GetPosition()
GetSpecies()
Move()
initialisesSpecies andDistancePerHour to the
parameter values; initialisesXPosition andYPosition
to 500.0
returns a string message that contains the horizontal and
vertical position of the bird
returns the species of the bird
takes a direction and number of minutes flying (between
0 and 500 inclusive) as parameters and updates the
appropriate horizontal or vertical position
A program stores data about birds using Object-Oriented Programming (OOP). |The class Bird stores the data about the birds: Bird|| |---|---| |**`Bird`**|**`Bird`**| |`DistancePerHour : Real`<br>`Species : String`<br>`XPosition : Real`<br>`YPosition : Real`|stores the number of kilometres per hour (km/h) the bird<br>can fly (between 0.0 and 100.0 inclusive)<br>stores the species of the bird, for example Pigeon<br>stores the current horizontal position of the bird<br>stores the current vertical position of the bird| |`Constructor()`<br>`GetPosition()`<br>`GetSpecies()`<br>`Move()`|initialises`Species` and`DistancePerHour` to the<br>parameter values; initialises`XPosition` and`YPosition` <br>to 500.0<br>returns a string message that contains the horizontal and<br>vertical position of the bird<br>returns the species of the bird<br>takes a direction and number of minutes flying (between<br>0 and 500 inclusive) as parameters and updates the<br>appropriate horizontal or vertical position|
Show mark scheme

1(a)(i)

Python class Bird: def init(self, pDistancePerHour, pSpecies): self.__Species = pSpecies #string self.__DistancePerHour = pDistancePerHour #real self.__XPosition = 500.0 #real self.__YPosition = 500.0 #real

1(a)(ii) [2 marks]

1 mark each • Get method header (and end) with no parameter …. • … returning Species Example program code Java public String GetSpecies(){ return Species; } VB.NET Function GetSpecies() Return Species End Function Python def GetSpecies(self): return self.__Species

1(a)(iii) [3 marks]

1 mark each • Get method header (and end) with no parameter, returning a value • Creating correct string using attributes … • … returning this string Example program code Java public String GetPosition(){ String ReturnValue = "X = " + XPosition + " Y = " + YPosition; return ReturnValue; } VB.NET Function GetPosition() Dim ReturnValue As String = "X = " & XPosition & " Y = " & YPosition Return ReturnValue End Function Python def GetPosition(self): ReturnValue = "X = " + str(self.__XPosition) + " Y = " + str(self.__YPosition) return ReturnValue

1(a)(iv)

VB.NET Function Move(Direction, MinsFlying) If Direction = "E" Then XPosition = XPosition + ((DistancePerHour / 60) * MinsFlying) ElseIf Direction = "W" Then XPosition = XPosition - ((DistancePerHour / 60) * MinsFlying) ElseIf Direction = "N" Then YPosition = YPosition + ((DistancePerHour / 60) * MinsFlying) ElseIf Direction = "S" Then YPosition = YPosition - ((DistancePerHour / 60) * MinsFlying) End If End Function Python def Move(self, Direction, MinsFlying): if Direction == "E": self.__XPosition = self.__XPosition + ((self.__DistancePerHour/60)*MinsFlying) elif Direction == "W": self.__XPosition = self.__XPosition - ((self.__DistancePerHour/60)*MinsFlying) elif Direction == "N": self.__YPosition = self.__YPosition + ((self.__DistancePerHour/60)*MinsFlying) elif Direction == "S": self.__YPosition = self.__YPosition - ((self.__DistancePerHour/60)*MinsFlying)

1(b) [3 marks]

1 mark each • Cockatiel 71.0 instance of created … Bird • Macaw 56.0 instance of created … Bird • … both stored in variables/structures Example program code Java Bird FirstBird = new Bird(71.0, "Cockatiel"); Bird SecondBird = new Bird(56.0, "Macaw"); VB.NET Dim FirstBird As Bird = New Bird(71.0, "Cockatiel") Dim SecondBird As Bird = New Bird(56.0, "Macaw") Python FirstBird = Bird(71.0, "Cockatiel") SecondBird = Bird(56.0, "Macaw")

1(c)(i)

Choice = int(input()) Time = -1 while Time < 0 || Time > 500: Time = int(input("To the nearest minute how long has the bird been flying ")) Valid = False while Valid == False: Valid = True Direction = input("Which direction has the bird been flying, North, South, East or West ").upper() if Direction == "NORTH" or Direction == "N": if Choice == 1: FirstBird.Move("N",Time) else: SecondBird.Move("N",Time) elif Direction == "SOUTH" or Direction == "S": if Choice == 1: FirstBird.Move("S",Time) else: SecondBird.Move("S",Time) elif Direction == "EAST" or Direction == "E": if Choice == 1: FirstBird.Move("E",Time) else: SecondBird.Move("E",Time) elif Direction == "WEST" or Direction == "W": if Choice == 1: FirstBird.Move("W",Time) else: SecondBird.Move("W",Time) else: Valid = False print(FirstBird.GetSpecies(), "is currently at", FirstBird.GetPosition()) print(SecondBird.GetSpecies(), "is currently at", SecondBird.GetPosition())

1(c)(ii) [3 marks]

1 mark for each: • screenshot showing inputs for one test with correct output • screenshot showing inputs for a second test with correct output • screenshot showing inputs for a third and fourth test with correct output e.g. Test 1: Test 2: Test 3: Test 4:

Q1
Oct/Nov 2025 Paper 4 v3

A program stores data for a board game using Object-Oriented Programming (OOP). The game

has objects that are placed on the board. Each object has a string code (for example "A") an integer value (for example, 2). The class BoardObject stores the data about the objects that can be placed on the board: BoardObject
BoardObject BoardObject
Code : String
Value : Integer
stores the board object’s code
stores the integer value of the board object
Constructor()
GetCode()
GetValue()
initialises the attributes to the parameter values
returnsCode
returnsValue

(a) (i) Write program code to declare the class BoardObject and its constructor. 5 marks

Do not declare the other methods.

Use your programming language appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program as Question1_N25 .

Copy and paste the program code into part 1(a)(i) in the evidence document.

A program stores data for a board game using Object-Oriented Programming (OOP). The game |has objects that are placed on the board. Each object has a string code (for example "A") an integer value (for example, 2). The class BoardObject stores the data about the objects that can be placed on the board: BoardObject|| |---|---| |**`BoardObject`**|**`BoardObject`**| |`Code : String`<br>`Value : Integer`|stores the board object’s code<br>stores the integer value of the board object| |`Constructor()`<br>`GetCode()`<br>`GetValue()`|initialises the attributes to the parameter values<br>returns`Code`<br>returns`Value`| **(a) (i)** Write program code to declare the class `BoardObject` and its constructor. <span class="part-marks">5 marks</span> Do **not** declare the other methods. Use your programming language appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program as **Question1_N25** . Copy and paste the program code into part **1(a)(i)** in the evidence document.
Show mark scheme

1(a)(i) [5 marks]

1 mark each • Class header (and end where appropriate) • Declaring as string and as integer Code Value • Constructor header (and end where appropriate) within class … • … taking two parameters … • … assigning parameters to attributes Example program code. Java class BoardObject{ public String Code; public Integer Value; public BoardObject(String pCode, Integer pValue){ Code = pCode; Value = pValue; } } VB.NET Public Class BoardObject Private Code As String Private Value As Integer Sub New(pCode, pValue) Code = pCode Value = pValue End Sub End Class Python class BoardObject(): def init(self, Code, Value): self.Code = Code #string self.Value = Value # integer

1(a)(ii) [3 marks]

1 mark each • 1 get header (and end where appropriate) with no parameter … • … returning correct value without overriding • 2nd correct get method Example program code Java public String GetCode(){ return Code; } public Integer GetValue(){ return Value; } VB.NET Function GetCode() Return Code End Function Function GetValue() Return Value End Function Python def GetCode(self): return self.Code def GetValue(self): return self.Value

1(a)(iii) [3 marks]

1 mark each • Creating one instance of and storing in correct variable … BoardObject • … with correct parameters • Remaining four created correctly and stored Example program code Java BoardObject Object1 = new BoardObject("A",2); BoardObject Object2 = new BoardObject("B",3); BoardObject Object3 = new BoardObject("C",5); BoardObject Object4 = new BoardObject("D",2); BoardObject Object5 = new BoardObject("E",7); VB.NET Dim Object1 As BoardObject = New BoardObject("A", 2) Dim Object2 As BoardObject = New BoardObject("B", 3) Dim Object3 As BoardObject = New BoardObject("C", 5) Dim Object4 As BoardObject = New BoardObject("D", 2) Dim Object5 As BoardObject = New BoardObject("E", 7) Python Object1 = BoardObject("A",2) Object2 = BoardObject("B",3) Object3 = BoardObject("C",5) Object4 = BoardObject("D",2) Object5 = BoardObject("E",7)

1(b)(i)

Python class Board(): def init(self): self.TheBoard = [] #type BoardObject for x in range(10): TempList = [] for y in range(10): TempList.append(BoardObject("-",0)) self.TheBoard.append(TempList)

1(b)(ii) [2 marks]

1 mark each • Get method header taking 2 (integer) parameters … • … returning the at position of parameters BoardObject Board Example program code Java public BoardObject GetObject(Integer Rowpos, Integer Columnpos){ return TheBoard[Rowpos][Columnpos]; } VB.NET Function GetObject(Rowpos, Columnpos) Return TheBoard(Rowpos, Columnpos) End Function Python def GetObject(self, Rowpos, Columnpos): return self.TheBoard[Rowpos][Columnpos]

1(b)(iii) [2 marks]

1 mark each • Set method header taking three parameters ( , row, column) … TheObject • … storing parameter in at parameters row and column TheObject TheBoard Example program code Java public void SetObject(BoardObject TheObject, Integer Rowpos, Integer Columnpos){ TheBoard[Rowpos][Columnpos] = TheObject; } VB.NET Sub SetObject(TheObject, Rowpos, Columnpos) TheBoard(Rowpos, Columnpos) = TheObject End Sub Python def SetObject(self, TheObject, Rowpos, Columnpos): self.TheBoard[Rowpos][Columnpos] = TheObject

1(b)(iv)

Python def DisplayBoard(self): for x in range(10): OutputLine = "" for y in range(10): OutputLine = OutputLine + str(self.TheBoard[x][y].GetCode()) + " " print(OutputLine)

1(c)(i)

Python GameBoard = Board() Object1 = BoardObject("A",2) Object2 = BoardObject("B",3) Object3 = BoardObject("C",5) Object4 = BoardObject("D",2) Object5 = BoardObject("E",7) GameBoard.SetObject(Object1, 0, 0) GameBoard.SetObject(Object2, 9, 9) GameBoard.SetObject(Object3, 4, 5) GameBoard.SetObject(Object4, 2, 2) GameBoard.SetObject(Object5, 8, 7) GameBoard.DisplayBoard()

1(c)(ii) [1 mark]

1 mark for screenshot showing board contents Example

1(d)(i)

While InputColumn < 0 Or InputColumn > 9 Console.WriteLine("Enter the column position between 0 and 9 ") InputColumn = Console.ReadLine() End While Dim GuessObject As BoardObject = GameBoard.GetObject(InputRow, InputColumn) If GuessObject.GetCode() = "-" Then Console.WriteLine("Miss") Else Console.WriteLine("You found " & GuessObject.GetCode() & " with value " & GuessObject.GetValue()) End If Python InputRow = -1 while InputRow < 0 or InputRow > 9: InputRow = int(input("Enter the row position between 0 and 9 ")) InputColumn = -1 while InputColumn < 0 or InputColumn > 9: InputColumn = int(input("Enter the column position between 0 and 9 ")) GuessObject = GameBoard.GetObject(InputRow, InputColumn) if GuessObject.GetCode() == "-": print("Miss") else: print("You found " + str(GuessObject.GetCode()) + " with value " + str(GuessObject.GetValue()))

1(d)(ii) [1 mark]

1 mark for screenshot showing inputs and correct output Row 10 4 Column -1 5 Output C 5 Example

Q11
May/Jun 2025 Paper 3 v1

(a) A medical centre uses objects of the class Appointment to record treatments given and medication prescribed during each doctor’s appointment. Some of the attributes required in the class are listed in the table. 5 marks

Attribute Data type Description
DateSeen DATE date of treatment
Treatments STRING treatments given
Medications STRING medications prescribed

Patients are identified by a unique 8-digit number, beginning with the patient’s year of birth, for example, 20108989. Doctors are identified by their name, for example, A N Other.

Complete the class diagram for Appointment, to include:

  • attribute and data type for the identification of the patient

  • attribute and data type for the identification of the doctor

  • methods to assign date seen, treatments given and medications prescribed

  • method to return the date seen and the attributes for the patient and the doctor.

Appointment

DateSeen : DATE

______ :

______ :

Treatments : STRING

Medications : STRING

SetPatientID(PatientNumber : INTEGER)

SetDoctor(DoctorID : STRING)

GetTreatments()

GetMedications()

(b) (i) Identify the object-oriented programming (OOP) feature whose function includes restricting external access to the data. 1 mark

(ii) Describe what is meant by the OOP feature inheritance. 2 marks

### (a) A medical centre uses objects of the class Appointment to record treatments given and medication prescribed during each doctor’s appointment. Some of the attributes required in the class are listed in the table. <span class="part-marks">5 marks</span> |Attribute|Data type|Description| |---|---|---| |DateSeen|DATE|date of treatment| |Treatments|STRING|treatments given| |Medications|STRING|medications prescribed| Patients are identified by a unique 8-digit number, beginning with the patient’s year of birth, for example, 20108989. Doctors are identified by their name, for example, A N Other. Complete the class diagram for Appointment, to include: - attribute and data type for the identification of the patient - attribute and data type for the identification of the doctor - methods to assign date seen, treatments given and medications prescribed - method to return the date seen and the attributes for the patient and the doctor. Appointment DateSeen : DATE ______ : ______ : Treatments : STRING Medications : STRING SetPatientID(PatientNumber : INTEGER) SetDoctor(DoctorID : STRING) GetTreatments() GetMedications() ### (b) (i) Identify the object-oriented programming (OOP) feature whose function includes restricting external access to the data. <span class="part-marks">1 mark</span> #### (ii) Describe what is meant by the OOP feature inheritance. <span class="part-marks">2 marks</span>
Show mark scheme

11(a) [5 marks]

One mark per mark point MP1 Two correct attributes ( and PatientID : INTEGER Doctor : STRING MP2 and seen SetTreatments(…) SetMedications(…) MP3 … and appropriate parameters, with string data types MP4 and seen GetPatientID() GetDoctor() MP5 and fully correct with appropriate parameter and correct data type in setter. SetDateSeen(…) GetDateSeen Appointment DateSeen : DATE PatientID : INTEGER Doctor : STRING Treatments : STRING Medications : STRING SetDateSeen(NewDate : DATE) SetPatientID(PatientNumber : INTEGER) SetDoctor(DoctorID : STRING) SetTreatments(NewTreatments : STRING) SetMedications(NewMedications : STRING) GetDateSeen() GetPatientID() GetDoctor() GetTreatments() GetMedications()

11(b)(i) [1 mark]

Encapsulation

11(b)(ii) [2 marks]

One mark for each mark point ( Max 2 ) MP1 Inheritance is where a derived class takes properties / behaviours attributes / methods MP2 … of a parent / super class / base class MP3 The attributes / methods / properties taken from the parent / super class / base class can also be extended / copied / used / changed / overwritten / overridden in the subclass.

Q12
May/Jun 2025 Paper 3 v2

(a) A medical clinic uses objects of the class Patient to assign a priority and a doctor to a patient. Some of the attributes required in the class are listed in the table. 5 marks

Attribute Data type Description
PatientID STRING Unique identifier of the patient
Name STRING Patient’s full name, surname first
DoctorID STRING ID of doctor administering treatment

Treatment is prioritised with a numeric scale of 1 to 5.

Complete the class diagram for Patient, to include:

  • attribute and data type for the date of birth

  • attribute and data type for the priority

  • methods to assign the patient ID, priority and doctor ID

  • methods to return the patient ID, patient date of birth and the priority.

Patient

PatientID : STRING

Name : STRING

______ :

______ :

DoctorID : STRING

SetName(FullName : STRING)

SetDateOfBirth(DOB : DATE)

GetName()

GetDoctorID()

### (a) A medical clinic uses objects of the class Patient to assign a priority and a doctor to a patient. Some of the attributes required in the class are listed in the table. <span class="part-marks">5 marks</span> |Attribute|Data type|Description| |---|---|---| |PatientID|STRING|Unique identifier of the patient| |Name|STRING|Patient’s full name, surname first| |DoctorID|STRING|ID of doctor administering treatment| Treatment is prioritised with a numeric scale of 1 to 5. Complete the class diagram for Patient, to include: - attribute and data type for the date of birth - attribute and data type for the priority - methods to assign the patient ID, priority and doctor ID - methods to return the patient ID, patient date of birth and the priority. Patient PatientID : STRING Name : STRING ______ : ______ : DoctorID : STRING SetName(FullName : STRING) SetDateOfBirth(DOB : DATE) GetName() GetDoctorID()
Show mark scheme

12(a) [5 marks]

One mark per mark point MP1 Two correct attributes ( ) and priority with a DateOfBirth : Date sensible name and integer data type MP2 and seen SetPatientID(…) SetDoctorID(…) MP3 … and appropriate parameters, with string data types MP4 and seen GetPatientID() GetDateOfBirth() MP5 Priority setter and getter fully correct with name matching Priority attribute, with appropriate parameter and correct data type. Patient PatientID : STRING Name : STRING DateOfBirth : DATE Priority : INTEGER DoctorID : STRING SetPatientID(PatientNumber : STRING) SetName(FullName : STRING) SetDateOfBirth(DOB : DATE) SetPriority(Urgency : INTEGER) SetDoctorID(DocID : STRING) GetPatientID() GetName() GetDateOfBirth() GetPriority() GetDoctorID()

12(b)(i) [1 mark]

Instance // instantiation

12(b)(ii) [2 marks]

One mark for each mark point MP1 Polymorphism is when methods with the same name are redefined / behave differently … MP2 … in derived / inherited classes / subclasses

Q5
May/Jun 2025 Paper 3 v3

Complete the table by filling in the missing object-oriented programming (OOP) terms and descriptions. 4 marks

OOP term Description
______ A method that accesses the value of a property.
______ A method that changes the value of a property.
Object

______
Method

______
Complete the table by filling in the missing object-oriented programming (OOP) terms and descriptions. <span class="part-marks">4 marks</span> |OOP term|Description| |---|---| |______|A method that accesses the value of a property.| |______|A method that changes the value of a property.| |Object|______<br>______<br>______| |Method|______<br>______<br>______|
Show mark scheme

5 [4 marks]

One mark per correct answer ( Max 4 ) OOP Term Purpose Getter A method that accesses the value of a property Setter A method that changes the value of a property Object An instantiation / instance of a class Method A programmed function / procedure / subroutine / subprogram defined as part of a class

Q3
May/Jun 2025 Paper 4 v1

A program stores data in a binary tree that is designed using Object‑Oriented Programming (OOP).

e stores data in ascending numerical order, for example:
30
20
45
63
33
1
21
30
20
45
63
33
1
21
1 63
The class Node stores data about the nodes. Node
Node Node
NodeData : Integer
LeftNode : Node
RightNode : Node
stores the node’s integer data
stores the node that is stored to the left of the current
node, or a null value if there is no node to the left
stores the node that is stored to the right of the current
node, or a null value if there is no node to the right
Constructor()
GetLeft()
GetRight()
GetData()
SetLeft()
SetRight()
initialisesNodeData to its parameter value; initialises
LeftNode andRightNode to a null value
returnsLeftNode
returnsRightNode
returnsNodeData
takes an object of typeNode as a parameter and stores
it inLeftNode
takes an object of typeNode as a parameter and stores
it inRightNode

(a) (i) Write program code to declare the class Node and its constructor. 4 marks

Do not declare the other methods.

Use your programming language appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program as Question3_J25 .

Copy and paste the program code into part 3(a)(i) in the evidence document.

(ii) Write program code for the three get methods. 3 marks

Save your program.

Copy and paste the program code into part 3(a)(ii) in the evidence document.

(iii) The method SetLeft() takes an object of type Node as a parameter. The method stores the parameter in the attribute LeftNode The method SetRight() takes an object of type Node as a parameter. The method stores the parameter in the attribute RightNode Write program code for SetLeft() and SetRight() Save your program. 3 marks

Copy and paste the program code into part 3(a)(iii) in the evidence document.

(b) Write the main program to declare five objects of type Node : 2 marks

  • Node 1 with the data 10

  • Node 2 with the data 20

  • Node 3 with the data 5

  • Node 4 with the data 15

  • Node 5 with the data 7

Save your program.

Copy and paste the program code into part 3(b) in the evidence document.

(c) The class Tree stores the tree. Tree
Tree Tree
FirstNode : Node stores the root node in the tree
Constructor()
GetRootNode()
Insert()
initialisesFirstNode to its parameter value
returns the node stored inFirstNode
stores its parameter node in the correct position in the
tree

(i) Write program code to declare the class Tree and its constructor. 2 marks

Do not declare the other methods.

Use your programming language appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program.

Copy and paste the program code into part 3(c)(i) in the evidence document.

(ii) Write program code for GetRootNode() Save your program. 1 mark

Copy and paste the program code into part 3(c)(ii) in the evidence document.

(iii) The method Insert() takes a node as a parameter and then searches the tree to find the position to insert the new node by: 6 marks

  • checking whether the node’s data is less than or greater than the root node’s data

  • moving to the left node if the data is less than the root node’s data

  • moving to the right node if the data is greater than or equal to the root node’s data

  • repeating until the final position of the node is found and stores the node in that position.

Write program code for Insert()

Save your program.

Copy and paste the program code into part 3(c)(iii) in the evidence document.

(d) The recursive procedure OutputInOrder() outputs the data stored in the binary tree in ascending numerical order. 5 marks

The procedure takes a Node object as a parameter and then:

  • checks if the left node is null. If there is a left node, the function calls itself with the left node

  • outputs the data of the current node

  • checks if the right node is null. If there is a right node, the function calls itself with the right node.

Write program code for OutputInOrder()

Save your program.

Copy and paste the program code into part 3(d) in the evidence document. (e) (i) Write program code to extend the main program to: 3 marks

  • create a new object of type Tree with the node containing the data 10 as the first node

  • insert the nodes with the values 20, 5, 15 and 7 into the tree in the order given

  • call OutputInOrder() with the tree’s root node as a parameter.

Save your program.

Copy and paste the program code into part 3(e)(i) in the evidence document.

(ii) Test your program. 1 mark

Take a screenshot of the output(s).

Save your program.

Copy and paste the screenshot into part 3(e)(ii) in the evidence document.

A program stores data in a binary tree that is designed using Object‑Oriented Programming (OOP). |e stores data in ascending numerical order, for example:|| |---|---| |30<br>20<br>45<br>63<br>33<br>1<br>21|30<br>20<br>45<br>63<br>33<br>1<br>21| |1|63| |The class Node stores data about the nodes. Node|| |---|---| |**`Node`**|**`Node`**| |`NodeData : Integer`<br>`LeftNode : Node`<br>`RightNode : Node`|stores the node’s integer data<br>stores the node that is stored to the left of the current<br>node, or a null value if there is no node to the left<br>stores the node that is stored to the right of the current<br>node, or a null value if there is no node to the right| |`Constructor()`<br>`GetLeft()`<br>`GetRight()`<br>`GetData()`<br>`SetLeft()`<br>`SetRight()`|initialises`NodeData` to its parameter value; initialises<br>`LeftNode` and`RightNode` to a null value<br>returns`LeftNode`<br>returns`RightNode`<br>returns`NodeData` <br>takes an object of type`Node` as a parameter and stores<br>it in`LeftNode`<br>takes an object of type`Node` as a parameter and stores<br>it in`RightNode`| **(a) (i)** Write program code to declare the class `Node` and its constructor. <span class="part-marks">4 marks</span> Do **not** declare the other methods. Use your programming language appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program as **Question3_J25** . Copy and paste the program code into part **3(a)(i)** in the evidence document. #### (ii) Write program code for the **three** get methods. <span class="part-marks">3 marks</span> Save your program. Copy and paste the program code into part **3(a)(ii)** in the evidence document. #### (iii) The method `SetLeft()` takes an object of type `Node` as a parameter. The method stores the parameter in the attribute `LeftNode` The method `SetRight()` takes an object of type `Node` as a parameter. The method stores the parameter in the attribute `RightNode` Write program code for `SetLeft()` and `SetRight()` Save your program. <span class="part-marks">3 marks</span> Copy and paste the program code into part **3(a)(iii)** in the evidence document. ### (b) Write the main program to declare **five** objects of type `Node` : <span class="part-marks">2 marks</span> - Node 1 with the data `10` - Node 2 with the data `20` - Node 3 with the data `5` - Node 4 with the data `15` - Node 5 with the data `7` Save your program. Copy and paste the program code into part **3(b)** in the evidence document. |(c) The class Tree stores the tree. Tree|| |---|---| |**`Tree`**|**`Tree`**| |`FirstNode : Node`|stores the root node in the tree| |`Constructor()`<br>`GetRootNode()`<br>`Insert()`|initialises`FirstNode` to its parameter value<br>returns the node stored in`FirstNode`<br>stores its parameter node in the correct position in the<br>tree| #### (i) Write program code to declare the class `Tree` and its constructor. <span class="part-marks">2 marks</span> Do **not** declare the other methods. Use your programming language appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into part **3(c)(i)** in the evidence document. #### (ii) Write program code for `GetRootNode()` Save your program. <span class="part-marks">1 mark</span> Copy and paste the program code into part **3(c)(ii)** in the evidence document. #### (iii) The method `Insert()` takes a node as a parameter and then searches the tree to find the position to insert the new node by: <span class="part-marks">6 marks</span> - checking whether the node’s data is less than or greater than the root node’s data - moving to the left node if the data is less than the root node’s data - moving to the right node if the data is greater than or equal to the root node’s data - repeating until the final position of the node is found and stores the node in that position. Write program code for `Insert()` Save your program. Copy and paste the program code into part **3(c)(iii)** in the evidence document. ### (d) The recursive procedure `OutputInOrder()` outputs the data stored in the binary tree in ascending numerical order. <span class="part-marks">5 marks</span> The procedure takes a `Node` object as a parameter and then: - checks if the left node is null. If there is a left node, the function calls itself with the left node - outputs the data of the current node - checks if the right node is null. If there is a right node, the function calls itself with the right node. Write program code for `OutputInOrder()` Save your program. Copy and paste the program code into part **3(d)** in the evidence document. **(e) (i)** Write program code to extend the main program to: <span class="part-marks">3 marks</span> - create a new object of type `Tree` with the node containing the data 10 as the first node - insert the nodes with the values 20, 5, 15 and 7 into the tree in the order given - call `OutputInOrder()` with the tree’s root node as a parameter. Save your program. Copy and paste the program code into part **3(e)(i)** in the evidence document. #### (ii) Test your program. <span class="part-marks">1 mark</span> Take a screenshot of the output(s). Save your program. Copy and paste the screenshot into part **3(e)(ii)** in the evidence document.
Show mark scheme

3(a)(i) [4 marks]

1 mark each • Class header (and end where appropriate) • Constructor header (and end where appropriate) with (min) one parameter (integer) within class • 3 attributes with correct data types • has parameter assigned, and are assigned null within constructor NodeData LeftNode RightNode

NodeData = pNodeData LeftNode = Nothing RightNode = Nothing

3(a)(ii) [3 marks]

1 mark each • 1 get method with no parameter … • … returning correct value • 2nd and 3rd correct get methods

3(a)(iii) [3 marks]

1 mark each • 1 set method taking parameter of type Node … • … assigning to correct attribute • 2nd correct set method

3(b) [2 marks]

1 mark each • Creating 1 instance of with a correct value and storing the node … Node • … remaining 4 correct

3(c)(i) [2 marks]

1 mark each • Class header (and end) no inheritance and constructor header (and end) taking 1 node parameter within class … Tree • … storing parameter in declared as a data type FirstNode Node FirstNode = pFirstNode FirstNode = pFirstNode;

3(c)(ii) [1 mark]

1 mark for • Get method header (and end) with no parameter, returning FirstNode

3(c)(iii) [6 marks]

1 mark each to max 6 • Insert method header (and end) taking 1 node parameter • If parameter < first node, checking if there is a left node … • … storing node in left node if it is null • If parameter >= first node, checking if there is a right node … • … storing node in right node if it is null • Looping until correct position is found // recursive calls

If NewNode.GetData() < CurrentNode.GetData() Then If CurrentNode.GetLeft() Is Nothing Then CurrentNode.SetLeft(NewNode) Return True Else CurrentNode = CurrentNode.GetLeft() End If

Else If CurrentNode.GetRight() Is Nothing Then CurrentNode.SetRight(NewNode) Return True Else CurrentNode = CurrentNode.GetRight() End If End If

3(d) [5 marks]

1 mark each • Procedure header (and end) taking node as parameter, that is recursive • Checking if left is null and recursive call if not null • Outputting node's data • Checking if right is null and recursive call if not null • Correct order

OutputInOrder(RootNode.GetLeft()) OutputInOrder(RootNode.GetRight())

3(e)(i) [3 marks]

1 mark each • Creation of object with the Node with value 10 as parameter Tree • Calling method for tree with the nodes for 20, 5, 15 and 7 in order Insert() • Calling with tree's root node as parameter OutputInOrder()

3(e)(ii) [1 mark]

Output of 5 7 10 15 20

Q3
May/Jun 2025 Paper 4 v2

A program stores data about animals using Object‑Oriented Programming (OOP).

The class Animal stores the data about animals. Animal
Animal Animal
Name : String
Sound : String
Size : Integer
Intelligence : Integer
stores the name of the animal
stores the sound the animal makes
stores the size of the animal as an integer between 1 (smallest)
and 10 (largest)
stores the intelligence of the animal as an integer between 1 (least)
and 10 (most)
Constructor()
Description()
initialises all attributes to its parameter values
returns a string message that contains the data from the attributes

(a) (i) Write program code to declare the class Animal and its constructor. 4 marks

Do not declare the other methods.

Use your programming language appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program as Question3_J25 .

Copy and paste the program code into part 3(a)(i) in the evidence document.

(ii) The method Description() creates and returns a string of the animal’s data in the format: 3 marks

      "The animal's name is " <Name> ", it makes a " <Sound> ", its size
      is " <Size> " and its intelligence level is " <Intelligence>

For example:

      The animal's name is Teddy, it makes a Bark, its size is 4 and its
      intelligence level is 6

Write program code for Description()

Save your program.

Copy and paste the program code into part 3(a)(ii) in the evidence document.

(b) The class Parrot inherits from the class Animal

Parrot inherits the attributes from Animal and overrides the Description() method. The additional attributes and methods in the class Parrot are: Parrot
Parrot Parrot
WingSpan : Integer
NumberWords : Integer
the width of the parrot’s wings to the nearest cm
the number of words the parrot can speak
Constructor()
ChangeNumberWords()
calls the parent constructor using its parameter values;
initialisesWingSpan andNumberWords to its parameter values
takes an integer parameter and adds this to the number currently
inNumberWords

(i) Write program code to declare the class Parrot, its constructor and the method 4 marks

      ChangeNumberWords()

Use your programming language appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program.

Copy and paste the program code into part 3(b)(i) in the evidence document.

(ii) The method Description() in the class Parrot creates and returns a string of the animal’s data in the format: 2 marks

      "The animal's name is " <Name> ", it makes a " <Sound> ", its size
      is " <Size> " and its intelligence level is " <Intelligence> ". It
      has a wingspan of " <WingSpan> "cm and can say " <NumberWords> "
      words."

For example:

      The animal's name is Chewie, it makes a Squawk, its size is 1 and
      its intelligence level is 10. It has a wingspan of 30cm and can
      say 29 words.

Write program code for Description()

Save your program.

Copy and paste the program code into part 3(b)(ii) in the evidence document.

(c) The class Wolf inherits from the class Animal

Wolf inherits the attributes from Animal and overrides the Description() method. The additional attributes and methods in the class Wolf are: Wolf
Wolf Wolf
TerritorySize : Integer stores the size of the area where the wolf lives, to the nearest
square mile
Constructor()
SetTerritorySize()
calls the parent constructor using its parameter values;
initialisesTerritorySize to its parameter value
takes an integer parameter and adds this to the number currently
inTerritorySize

(i) Write program code to declare the class Wolf, its constructor and the method 4 marks

      SetTerritorySize()

Use your programming language appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program.

Copy and paste the program code into part 3(c)(i) in the evidence document.

(ii) The method Description() in the class Wolf creates and returns a string of the animal’s data in the format: 2 marks

      "The animal's name is " <Name> ", it makes a " <Sound> ", its size
      is " <Size> " and its intelligence level is " <Intelligence> ".
      Its territory is " <TerritorySize> " square miles."

For example:

      The animal's name is Nighteyes, it makes a Howl, its size is 8 and
      its intelligence level is 7. Its territory is 100 square miles.

Write program code for Description()

Save your program.

Copy and paste the program code into part 3(c)(ii) in the evidence document. (d) (i) The main program declares instances of the classes for three animals: 2 marks

  • A parrot with the name ‘Chewie’; it makes a ‘Squawk’ sound. Its size is 1, intelligence is 10, wingspan is 30 cm and it can say 29 words.

  • A wolf with the name ‘Nighteyes’; it makes a ‘Howl’ sound. Its size is 8, intelligence is 7 and its territory is 100 square miles.

  • An animal that is a horse with the name ‘Copper’; it makes a ‘Neigh’ sound. Its size is 10 and its intelligence is 6.

Write program code for the main program.

Save your program.

Copy and paste the program code into part 3(d)(i) in the evidence document.

(ii) The main program also needs to: 3 marks

  • decrease the territory for the wolf Nighteyes by 20 square miles

  • increase the number of words the parrot Chewie can say by 2 words

  • output the description for all three animals.

Write program code to extend the main program.

Save your program.

Copy and paste the program code into part 3(d)(ii) in the evidence document.

(iii) Test your program. 2 marks

Take a screenshot of the output(s).

Save your program.

Copy and paste the screenshot into part 3(d)(iii) in the evidence document.

A program stores data about animals using Object‑Oriented Programming (OOP). |The class Animal stores the data about animals. Animal|| |---|---| |**`Animal`**|**`Animal`**| |`Name : String`<br>`Sound : String`<br>`Size : Integer`<br>`Intelligence : Integer`|stores the name of the animal<br>stores the sound the animal makes<br>stores the size of the animal as an integer between 1 (smallest)<br>and 10 (largest)<br>stores the intelligence of the animal as an integer between 1 (least)<br>and 10 (most)| |`Constructor()`<br>`Description()`|initialises all attributes to its parameter values<br>returns a string message that contains the data from the attributes| **(a) (i)** Write program code to declare the class `Animal` and its constructor. <span class="part-marks">4 marks</span> Do **not** declare the other methods. Use your programming language appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program as **Question3_J25** . Copy and paste the program code into part **3(a)(i)** in the evidence document. #### (ii) The method `Description()` creates and returns a string of the animal’s data in the format: <span class="part-marks">3 marks</span> ``` "The animal's name is " <Name> ", it makes a " <Sound> ", its size is " <Size> " and its intelligence level is " <Intelligence> ``` For example: ``` The animal's name is Teddy, it makes a Bark, its size is 4 and its intelligence level is 6 ``` Write program code for `Description()` Save your program. Copy and paste the program code into part **3(a)(ii)** in the evidence document. ### (b) The class `Parrot` inherits from the class `Animal` |Parrot inherits the attributes from Animal and overrides the Description() method. The additional attributes and methods in the class Parrot are: Parrot|| |---|---| |**`Parrot`**|**`Parrot`**| |`WingSpan : Integer`<br>`NumberWords : Integer`|the width of the parrot’s wings to the nearest cm<br>the number of words the parrot can speak| |`Constructor()`<br>`ChangeNumberWords()`|calls the parent constructor using its parameter values;<br>initialises`WingSpan` and`NumberWords` to its parameter values<br>takes an integer parameter and adds this to the number currently<br>in`NumberWords`| #### (i) Write program code to declare the class `Parrot`, its constructor and the method <span class="part-marks">4 marks</span> ``` ChangeNumberWords() ``` Use your programming language appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into part **3(b)(i)** in the evidence document. #### (ii) The method `Description()` in the class `Parrot` creates and returns a string of the animal’s data in the format: <span class="part-marks">2 marks</span> ``` "The animal's name is " <Name> ", it makes a " <Sound> ", its size is " <Size> " and its intelligence level is " <Intelligence> ". It has a wingspan of " <WingSpan> "cm and can say " <NumberWords> " words." ``` For example: ``` The animal's name is Chewie, it makes a Squawk, its size is 1 and its intelligence level is 10. It has a wingspan of 30cm and can say 29 words. ``` Write program code for `Description()` Save your program. Copy and paste the program code into part **3(b)(ii)** in the evidence document. ### (c) The class `Wolf` inherits from the class `Animal` |Wolf inherits the attributes from Animal and overrides the Description() method. The additional attributes and methods in the class Wolf are: Wolf|| |---|---| |**`Wolf`**|**`Wolf`**| |`TerritorySize : Integer`|stores the size of the area where the wolf lives, to the nearest<br>square mile| |`Constructor()`<br>`SetTerritorySize()`|calls the parent constructor using its parameter values;<br>initialises`TerritorySize` to its parameter value<br>takes an integer parameter and adds this to the number currently<br>in`TerritorySize`| #### (i) Write program code to declare the class `Wolf`, its constructor and the method <span class="part-marks">4 marks</span> ``` SetTerritorySize() ``` Use your programming language appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into part **3(c)(i)** in the evidence document. #### (ii) The method `Description()` in the class `Wolf` creates and returns a string of the animal’s data in the format: <span class="part-marks">2 marks</span> ``` "The animal's name is " <Name> ", it makes a " <Sound> ", its size is " <Size> " and its intelligence level is " <Intelligence> ". Its territory is " <TerritorySize> " square miles." ``` For example: ``` The animal's name is Nighteyes, it makes a Howl, its size is 8 and its intelligence level is 7. Its territory is 100 square miles. ``` Write program code for `Description()` Save your program. Copy and paste the program code into part **3(c)(ii)** in the evidence document. **(d) (i)** The main program declares instances of the classes for **three** animals: <span class="part-marks">2 marks</span> - A parrot with the name ‘Chewie’; it makes a ‘Squawk’ sound. Its size is 1, intelligence is 10, wingspan is 30 cm and it can say 29 words. - A wolf with the name ‘Nighteyes’; it makes a ‘Howl’ sound. Its size is 8, intelligence is 7 and its territory is 100 square miles. - An animal that is a horse with the name ‘Copper’; it makes a ‘Neigh’ sound. Its size is 10 and its intelligence is 6. Write program code for the main program. Save your program. Copy and paste the program code into part **3(d)(i)** in the evidence document. #### (ii) The main program also needs to: <span class="part-marks">3 marks</span> - decrease the territory for the wolf Nighteyes by 20 square miles - increase the number of words the parrot Chewie can say by 2 words - output the description for all **three** animals. Write program code to extend the main program. Save your program. Copy and paste the program code into part **3(d)(ii)** in the evidence document. #### (iii) Test your program. <span class="part-marks">2 marks</span> Take a screenshot of the output(s). Save your program. Copy and paste the screenshot into part **3(d)(iii)** in the evidence document.
Show mark scheme

3(a)(i) [4 marks]

1 mark each • Class header (and end when appropriate) • Four attributes with appropriate data types • Constructor header (and end where appropriate) within class taking (min) 4 parameters … • … assigning each parameter to its attribute

public String Name; public String Sound; public Integer Size; public Integer Intelligence; public Animal(String pName, String pSound, Integer pSize, Integer pIntelligence){ Name = pName; Sound = pSound; Size = pSize; Intelligence = pIntelligence; }

3(a)(ii) [3 marks]

1 mark each • method header (and end where appropriate) with no parameter Description() • Concatenating the attributes with the given message … • … and returning the created message String Message = "The animal's name is " + Name + ", it makes a " + Sound + ", its size is " + Size

3(b)(i) [4 marks]

1 mark each • Class header (and end where appropriate) inherits from Animal • Constructor header (and end where appropriate) taking 6 parameters within class the four parameters … • and attributes defined with data types and parameters assigned within constructor … WingSpan NumberWords • method header (and end where appropriate) takes one parameter ChangeNumberWords() attribute NumberWords public Integer WingSpan; public Integer NumberWords; public Parrot(String pName, String pSound, Integer pSize, Integer pIntelligence, Integer pWingSpan, super(pName, pSound, pSize, pIntelligence); WingSpan = pWingSpan; NumberWords = pNumberWords; } public void ChangeNumberWords(Integer Change){ NumberWords = NumberWords + Change; }}

3(b)(ii) [2 marks]

1 mark each • method header (and end where appropriate) taking no Description() overriding/overloads/extending/using parent method • Concatenating and returning the correct string String Message = "The animal's name is " + Name + ", it makes a " + Sound + ", its size is " + Size

3(c)(i) [4 marks]

1 mark each • Class header (and end where appropriate) inherits from Animal • Constructor header (and end where appropriate) taking 5 parameters within class parameters • Attribute defined as int and parameter assigned within constructor Territory • method header (and end) takes 1 parameter and adds parameter to attribute SetTerritory() public Integer TerritorySize; public Wolf(String pName, String pSound, Integer pSize, Integer pIntelligence, Integer super(pName, pSound, pSize, pIntelligence); TerritorySize = pTerritorySize; } public void SetTerritorySize(Integer Change){ TerritorySize = TerritorySize + Change; }}

3(c)(ii) [2 marks]

1 mark each • method header (and end where appropriate) taking no Description() overriding/overloads/extending/using parent method • Concatenating and return correct message String Message = "The animal's name is " + Name + ", it makes a " + Sound + ", its size is " + Size

3(d)(i) [2 marks]

1 mark each • 1 correct instance created and stored in a suitable variable/structure • 2nd and 3rd correct instances created and stored in a suitable variable/structure

3(d)(ii) [3 marks]

1 mark each • Calling for instance of Nighteyes SetTerritorySize(-20) • Calling for instance of Chewie ChangeNumberWords(2) • Calling for all 3 animals (after any updates) and outputting return values Description()

3(d)(iii) [2 marks]

1 mark each: • All three messages accurate with all relevant values • … showing correctly updated territory for Nighteyes and words for Chewie

Q3
May/Jun 2025 Paper 4 v3

A program stores data in a linked list that is designed using Object‑Oriented Programming (OOP).

The class Node stores data about the nodes.

Node
TheData : Integer
NextNode : Node
stores the integer data
stores the next node in the linked list
Constructor()
GetData()
GetNextNode()
SetNextNode()
initialisesTheData to its parameter value, initialisesNextNode
to a null value
returnsTheData
returnsNextNode
takes an object of typeNode as a parameter and stores it in
NextNode

(a) (i) Write program code to declare the class Node and its constructor. 4 marks

Do not declare the other methods.

Use your programming language appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program as Question3_J25 .

Copy and paste the program code into part 3(a)(i) in the evidence document.

(ii) Write program code for the two get methods. 3 marks

Save your program.

Copy and paste the program code into part 3(a)(ii) in the evidence document.

(iii) The method SetNextNode() takes an object of type Node as a parameter. The method stores the parameter in the attribute NextNode Write program code for SetNextNode() Save your program. 2 marks

Copy and paste the program code into part 3(a)(iii) in the evidence document.

The class LinkedList stores the linked list. LinkedList
LinkedList LinkedList
HeadNode : Node stores the first node in the linked list
Constructor()
InsertNode()
RemoveNode()
Traverse()
initialisesHeadNode to a null value
creates a new node using its integer parameter. Sets this
node as the new head node and updatesNextNode
finds the first node that contains its integer parameter and
removes this node from the linked list
concatenates and returns the integer data in each node in
the linked list

(i) Write program code to declare the class LinkedList and its constructor.

Do not declare the other methods.

Use your programming language appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program.

Copy and paste the program code into part 3(b)(i) in the evidence document.

(ii) The method InsertNode() : 2 marks 4 marks

  • takes an integer as a parameter

  • creates a new node with the parameter as the integer data

  • uses the new node’s method SetNextNode() to store the current HeadNode as the next node

  • replaces HeadNode with the current node.

Write program code for InsertNode()

Save your program.

Copy and paste the program code into part 3(b)(ii) in the evidence document.

(iii) The method Traverse() concatenates the integer data from the nodes in the linked list, starting with the node stored in HeadNode . The method returns the final string with each integer data separated with a space. 3 marks

Write program code for Traverse()

Save your program.

Copy and paste the program code into part 3(b)(iii) in the evidence document.

(iv) The method RemoveNode() takes an integer parameter to search for and remove from the linked list. 6 marks

The method first checks if the linked list is empty. If the linked list is empty the method returns FALSE

If the linked list is not empty, the integer data in HeadNode is compared to the parameter. If it matches the parameter, HeadNode is changed to store the next node.

If the parameter does not match, the nodes are followed until either:

  • the node with matching integer data is found. This node is removed, the appropriate nodes updated and TRUE returned

  • or

  • none of the nodes contain matching integer data to the parameter. No nodes are removed and FALSE is returned.

Write program code for RemoveNode()

Save your program.

Copy and paste the program code into part 3(b)(iv) in the evidence document. (c) (i) The main program creates a new LinkedList object and uses the appropriate method 3 marks to insert five nodes with the following integer data values in the order given:

              10  20  30  40  50

The main program then:

  • calls Traverse()

  • removes the node containing the integer data 30 using RemoveNode()

  • calls Traverse()

Write program code for the main program.

Save your program.

Copy and paste the program code into part 3(c)(i) in the evidence document.

(ii) Test your program. 2 marks

Take a screenshot of the output(s).

Save your program.

Copy and paste the screenshot into part 3(c)(ii) in the evidence document.

A program stores data in a linked list that is designed using Object‑Oriented Programming (OOP). The class `Node` stores data about the nodes. |Node|| |---|---| |`TheData : Integer`<br>`NextNode : Node`|stores the integer data<br>stores the next node in the linked list| |`Constructor()`<br>`GetData()`<br>`GetNextNode()`<br>`SetNextNode()`|initialises`TheData` to its parameter value, initialises`NextNode` <br>to a null value<br>returns`TheData`<br>returns`NextNode`<br>takes an object of type`Node` as a parameter and stores it in<br>`NextNode`| **(a) (i)** Write program code to declare the class `Node` and its constructor. <span class="part-marks">4 marks</span> Do **not** declare the other methods. Use your programming language appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program as **Question3_J25** . Copy and paste the program code into part **3(a)(i)** in the evidence document. #### (ii) Write program code for the **two** get methods. <span class="part-marks">3 marks</span> Save your program. Copy and paste the program code into part **3(a)(ii)** in the evidence document. #### (iii) The method `SetNextNode()` takes an object of type `Node` as a parameter. The method stores the parameter in the attribute `NextNode` Write program code for `SetNextNode()` Save your program. <span class="part-marks">2 marks</span> Copy and paste the program code into part **3(a)(iii)** in the evidence document. |The class LinkedList stores the linked list. LinkedList|| |---|---| |**`LinkedList`**|**`LinkedList`**| |`HeadNode : Node`|stores the first node in the linked list| |`Constructor()`<br>`InsertNode()`<br>`RemoveNode()`<br>`Traverse()`|initialises`HeadNode` to a null value<br>creates a new node using its integer parameter. Sets this<br>node as the new head node and updates`NextNode`<br>finds the first node that contains its integer parameter and<br>removes this node from the linked list<br>concatenates and returns the integer data in each node in<br>the linked list| #### (i) Write program code to declare the class `LinkedList` and its constructor. Do **not** declare the other methods. Use your programming language appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into part **3(b)(i)** in the evidence document. #### (ii) The method `InsertNode()` : <span class="part-marks">2 marks</span> <span class="part-marks">4 marks</span> - takes an integer as a parameter - creates a new node with the parameter as the integer data - uses the new node’s method `SetNextNode()` to store the current `HeadNode` as the next node - replaces `HeadNode` with the current node. Write program code for `InsertNode()` Save your program. Copy and paste the program code into part **3(b)(ii)** in the evidence document. #### (iii) The method `Traverse()` concatenates the integer data from the nodes in the linked list, starting with the node stored in `HeadNode` . The method returns the final string with each integer data separated with a space. <span class="part-marks">3 marks</span> Write program code for `Traverse()` Save your program. Copy and paste the program code into part **3(b)(iii)** in the evidence document. #### (iv) The method `RemoveNode()` takes an integer parameter to search for and remove from the linked list. <span class="part-marks">6 marks</span> The method first checks if the linked list is empty. If the linked list is empty the method returns `FALSE` If the linked list is **not** empty, the integer data in `HeadNode` is compared to the parameter. If it matches the parameter, `HeadNode` is changed to store the next node. If the parameter does **not** match, the nodes are followed until either: - the node with matching integer data is found. This node is removed, the appropriate nodes updated and `TRUE` returned - or - none of the nodes contain matching integer data to the parameter. No nodes are removed and `FALSE` is returned. Write program code for `RemoveNode()` Save your program. Copy and paste the program code into part **3(b)(iv)** in the evidence document. **(c) (i)** The main program creates a new `LinkedList` object and uses the appropriate method <span class="part-marks">3 marks</span> to insert **five** nodes with the following integer data values in the order given: ``` 10 20 30 40 50 ``` The main program then: - calls `Traverse()` - removes the node containing the integer data `30` using `RemoveNode()` - calls `Traverse()` Write program code for the main program. Save your program. Copy and paste the program code into part **3(c)(i)** in the evidence document. #### (ii) Test your program. <span class="part-marks">2 marks</span> Take a screenshot of the output(s). Save your program. Copy and paste the screenshot into part **3(c)(ii)** in the evidence document.
Show mark scheme

3(a)(i) [4 marks]

1 mark each • Class header (and end) Node • declared as Integer, declared as TheData NextNode Node • Constructor header (and end) taking (min) 1 parameter … • … storing parameter to within constructor and storing null value to TheData TheData = NodeData NextNode = Nothing

3(a)(ii) [3 marks]

1 mark each • 1 get method header (and close) taking no parameters … • … returning correct value (without overwriting) • 2nd correct get method

3(a)(iii) [2 marks]

1 mark each • method header (and close) taking 1 parameter (of type SetNextNode() • … storing parameter in NextNode

3(b)(i) [2 marks]

1 mark each • Class header (and close) and constructor header with no parameter (and close) … LinkedList • … declaring as type and storing null value in constructor HeadNode Node HeadNode = Nothing

3(b)(ii) [4 marks]

1 mark each • method header (and close) taking one (integer) parameter InsertNode() • Creating new instance of with the parameter as the argument Node • Calling for new node with as parameter SetNextNode() HeadNode • Replacing with new node HeadNode

3(b)(iii) [3 marks]

1 mark each • method header (and close) with no parameter and returns created string Traverse() • Starts at head node and follows nodes using until no nodes left … GetNextNode() • … concatenates the data from each node and formats correctly

ReturnValue = ReturnValue & CurrentNode.GetData() & " " CurrentNode = CurrentNode.GetNextNode()

3(b)(iv) [6 marks]

1 mark each to max 6 • method header (and close) taking (integer) parameter and returning Boolean in all cases RemoveNode() • Checking if head node is null and returning FALSE • Checking if head node equals parameter and returning if true … TRUE • … and updating to HeadNode HeadNode.GetNextNode() • Following nodes comparing data from each node to parameter … • ... if found updating next node and returning TRUE • … if end of list returning FALSE

Return False HeadNode = HeadNode.GetNextNode() Return True If ((CurrentNode).GetNextNode()).GetData() = DataToRemove Then CurrentNode.SetNextNode(CurrentNode.GetNextNode().GetNextNode()) Found = True Else CurrentNode = CurrentNode.GetNextNode() End If

3(c)(i) [3 marks]

1 mark each • Creating new object LinkedList • Calling five times with correct data in correct order InsertNode() • Calling and calling and store/output the return value, before RemoveNode(30) Traverse() after Full marks can be awarded to students who may have stored and/or outputted the return value from the function call.

3(c)(ii) [2 marks]

1 mark each • Output of linked list with 50 40 30 20 10 • Output of 2nd linked list with 50 40 20 10

Q9
Oct/Nov 2024 Paper 3 v1

A veterinary surgery wants to create a class for individual pets. Some of the attributes required in the class are listed in the table.

Attribute Data type Description
PetID STRING unique ID assigned at registration
PetType STRING type of pet assigned at registration
OwnerTelephone STRING telephone number of owner assigned at
registration
DateRegistered DATE date of registration

(a) State one reason why the attributes would be declared as PRIVATE. 1 mark

(b) Complete the class diagram for Pet, to include: 5 marks

  • an attribute and data type for the name of the pet

  • an attribute and data type for the name of the owner

  • a method to create a Pet object and set attributes at the time of registration

  • a method to assign a pet ID

  • a method to assign the date of registration

  • a method to return the pet name

  • a method to return the owner’s telephone number.

Pet

PetID : STRING

PetType : STRING

OwnerTelephone : STRING

DateRegistered : DATE

______ :

______ :

A veterinary surgery wants to create a class for individual pets. Some of the attributes required in the class are listed in the table. |Attribute|Data type|Description| |---|---|---| |PetID|STRING|unique ID assigned at registration| |PetType|STRING|type of pet assigned at registration| |OwnerTelephone|STRING|telephone number of owner assigned at<br>registration| |DateRegistered|DATE|date of registration| ### (a) State one reason why the attributes would be declared as PRIVATE. <span class="part-marks">1 mark</span> ### (b) Complete the class diagram for Pet, to include: <span class="part-marks">5 marks</span> - an attribute and data type for the name of the pet - an attribute and data type for the name of the owner - a method to create a Pet object and set attributes at the time of registration - a method to assign a pet ID - a method to assign the date of registration - a method to return the pet name - a method to return the owner’s telephone number. Pet PetID : STRING PetType : STRING OwnerTelephone : STRING DateRegistered : DATE ______ : ______ :
Show mark scheme

9(a) [1 mark]

To ensure that the attributes are only accessible using the class’s own methods/within the class.

9(b) [5 marks]

One mark per mark point ( Max 5 ) MP1 Two correct attributes with sensible names and correct data types. MP2 Constructor present. MP3 Two correct setters with exact names and appropriate parameters and data types. MP4 Two correct getters with appropriate names. MP5 Name assigned to pet name getter matches the attribute. Pet PetID : STRING PetType : STRING OwnerTelephone : STRING DateRegistered : DATE PetName : STRING OwnerName : STRING Constructor() SetPetID(APetID : STRING) SetDateRegistered(RegDate : DATE) GetPetName() GetOwnerTelephone()

Q10
Oct/Nov 2024 Paper 3 v2

Objects and classes form the basic structure of Object‑Oriented Programming (OOP).

(a) Outline the structure of a class. 3 marks

(b) Give three differences between an object and a class. 3 marks

1

2

3

Objects and classes form the basic structure of Object‑Oriented Programming (OOP). ### (a) Outline the structure of a class. <span class="part-marks">3 marks</span> ### (b) Give three differences between an object and a class. <span class="part-marks">3 marks</span> 1 2 3
Show mark scheme

10(a) [3 marks]

One mark per mark point ( Max 3) MP1 Attributes/properties … MP2 … with their data types // … are variables bound to the class MP3 Methods … MP4 … that are subroutines / functions / procedures that act upon the attributes MP5 Getters/setters … MP6 … are methods that can fetch / update the contents of attributes MP7 A constructor … MP8 … that is used to create instances / objects of this class.

10(b) [3 marks]

One mark per mark point ( Max 3) MP1 A class is only defined once but many objects can be created from that class // A class is a template / blueprint from which objects are created // An object is an instance of a class MP2 No memory is allocated when a class is defined, but objects are allocated memory space whenever they are created MP3 A class cannot be manipulated as it is not available in the memory, but objects can be manipulated MP4 A class is defined but an object is declared / created / instantiated. MP5 A class can use inheritance. An object cannot.

Q9
Oct/Nov 2024 Paper 3 v3

A veterinary surgery wants to create a class for individual pets. Some of the attributes required in the class are listed in the table.

Attribute Data type Description
PetID STRING unique ID assigned at registration
PetType STRING type of pet assigned at registration
OwnerTelephone STRING telephone number of owner assigned at
registration
DateRegistered DATE date of registration

(a) State one reason why the attributes would be declared as PRIVATE. 1 mark

(b) Complete the class diagram for Pet, to include: 5 marks

  • an attribute and data type for the name of the pet

  • an attribute and data type for the name of the owner

  • a method to create a Pet object and set attributes at the time of registration

  • a method to assign a pet ID

  • a method to assign the date of registration

  • a method to return the pet name

  • a method to return the owner’s telephone number.

Pet

PetID : STRING

PetType : STRING

OwnerTelephone : STRING

DateRegistered : DATE

______ :

______ :

A veterinary surgery wants to create a class for individual pets. Some of the attributes required in the class are listed in the table. |Attribute|Data type|Description| |---|---|---| |PetID|STRING|unique ID assigned at registration| |PetType|STRING|type of pet assigned at registration| |OwnerTelephone|STRING|telephone number of owner assigned at<br>registration| |DateRegistered|DATE|date of registration| ### (a) State one reason why the attributes would be declared as PRIVATE. <span class="part-marks">1 mark</span> ### (b) Complete the class diagram for Pet, to include: <span class="part-marks">5 marks</span> - an attribute and data type for the name of the pet - an attribute and data type for the name of the owner - a method to create a Pet object and set attributes at the time of registration - a method to assign a pet ID - a method to assign the date of registration - a method to return the pet name - a method to return the owner’s telephone number. Pet PetID : STRING PetType : STRING OwnerTelephone : STRING DateRegistered : DATE ______ : ______ :
Show mark scheme

9(a) [1 mark]

To ensure that the attributes are only accessible using the class’s own methods/within the class.

9(b) [5 marks]

One mark per mark point ( Max 5 ) MP1 Two correct attributes with sensible names and correct data types. MP2 Constructor present. MP3 Two correct setters with exact names and appropriate parameters and data types. MP4 Two correct getters with appropriate names. MP5 Name assigned to pet name getter matches the attribute. Pet PetID : STRING PetType : STRING OwnerTelephone : STRING DateRegistered : DATE PetName : STRING OwnerName : STRING Constructor() SetPetID(APetID : STRING) SetDateRegistered(RegDate : DATE) GetPetName() GetOwnerTelephone()

Q2
Oct/Nov 2024 Paper 4 v1

A computer program is designed to simulate horses doing show jumping. In show jumping, horses jump over obstacles called fences. A horse successfully jumps a fence if it does not knock the fence down.

The program is written using Object-Oriented Programming (OOP).

The class Horse stores data about the horses.
Horse Horse
Name : STRING
MaxFenceHeight : INTEGER
PercentageSuccess : INTEGER
stores the name given to the horse
stores the maximum height in cm that the horse can
jump, for example 132
stores the percentage chance of a horse not knocking
down a fence, for example 70 represents a 70% chance
of jumping a fence successfully
Constructor()
GetName()
GetMaxFenceHeight()
Success()
initialisesName, MaxFenceHeight and
PercentageSuccess to its parameter values
returns the name of the horse
returns the maximum height the horse can jump
calculates and returns the percentage chance of a horse
successfully jumping a specific fence

(a) (i) Write program code to declare the class Horse and its constructor. 4 marks

Do not declare the other methods.

Use your programming language’s appropriate constructor.

All attributes must be private. If you are writing in Python, include attribute declarations using comments.

Save your program as Question2_N24 .

Copy and paste the program code into part 2(a)(i) in the evidence document.

(ii) The get methods GetName() and GetMaxFenceHeight() each return the relevant attribute. 3 marks

Write program code for the get methods.

Save your program.

Copy and paste the program code into part 2(a)(ii) in the evidence document.

(b) The array Horses stores objects of type Horse .

(i) The program has two horses: 5 marks

  • The horse named ‘Beauty’ can jump a maximum height of 150 cm and has a success percentage rate of 72%.

  • The horse named ‘Jet’ can jump a maximum height of 160 cm and has a success percentage rate of 65%.

Write program code to:

  • declare the array, Horses, local to the main program with space for two Horse objects

  • store the two horses described in the array

  • output the name of both Horse objects from the array.

Save your program.

Copy and paste the program code into part 2(b)(i) in the evidence document.

(ii) Test your program. 1 mark

Take a screenshot of the output.

Save your program.

Copy and paste the screenshot into part 2(b)(ii) in the evidence document.

(c) The class Fence stores data about the fences. Each fence has a height in cm and a risk number.

The risk is a whole number between 1 and 5 inclusive. A risk of 1 means the fence is the easiest type to jump. A risk of 5 means the fence is the hardest type to jump.
Fence Fence
Height : INTEGER
Risk : INTEGER
stores the height of the fence in cm
the height is between 70 and 180 inclusive
stores the risk as a whole number between 1 and 5
inclusive
Constructor()
GetHeight()
GetRisk()
initialisesHeight andRisk to its parameter values
returns the height of the fence
returns the risk of the fence

(i) Write program code to declare the class Fence, its constructor and get methods. 4 marks

Use your programming language’s appropriate constructor.

All attributes must be private.

If you are writing in Python, include attribute declarations using comments.

Save your program.

Copy and paste the program code into part 2(c)(i) in the evidence document.

(ii) The array Course stores four Fence objects. The user inputs the height and risk for each fence, and these are validated before each fence is created. 5 marks

Amend the main program to:

  • declare the local array Course

  • take as input the data for four fences from the user

  • loop the input until both the height and risk are valid for each fence

  • create an instance of Fence for each of the four valid fences and store each instance in the array.

Save your program.

Copy and paste the program code into part 2(c)(ii) in the evidence document.

(d) The chance of a horse jumping a fence without knocking it down is calculated as follows. 5 marks

If the height of the fence is more than the maximum height a horse can jump, the success percentage is 20% of the horse’s PercentageSuccess . The risk does not affect this value.

If the height of the fence is less than or equal to the maximum height a horse can jump, the risk gives a modifier value to multiply with the horse’s PercentageSuccess .

The risk values and their modifiers are given in this table:

Risk Modifier
5 0.6
4 0.7
3 0.8
2 0.9
1 1.0

For example:

  • The horse Jet has PercentageSuccess of 65 and MaxFenceHeight of 160.

  • A fence has a height of 140 and a risk of 3.

  • The height of the fence is less than the horse’s MaxFenceHeight, therefore the risk is used.

  • The risk of 3 gives the modifier 0.8.

  • The modifier 0.8 is multiplied by the horse’s PercentageSuccess of 65, which gives 52.

  • The chance of the horse successfully jumping this fence is 52%.

The method Success() in the Horse class:

  • takes the height and risk of a fence as parameters

  • calculates the percentage chance of success for that horse jumping the fence without knocking it down

  • returns the calculated percentage chance of success as a real number.

Write program code for Success() .

Save your program.

Copy and paste the program code into part 2(d) in the evidence document. (e) (i) Write program code to amend the main program to: 3 marks

  • calculate and output the chance of the first horse jumping each of the four fences without knocking each fence down

  • calculate and output the chance of the second horse jumping each of the four fences without knocking each fence down.

All outputs must have appropriate messages including the name of the horse and the fence number.

An example output for one horse jumping two fences is:

     "The horse Fox at fence 1 has a 68% chance of success
     The horse Fox at fence 2 has a 72% chance of success"

Save your program.

Copy and paste the program code into part 2(e)(i) in the evidence document.

(ii) Write program code to amend the main program to: 2 marks 2 marks

  • calculate and output the average chance of success for each horse jumping over all four fences without knocking each fence down (the average is the total of values divided by the quantity of values). An example output for one horse jumping all of the fences is:
      "The horse Fox has an average 70% chance of jumping over all four
      fences"
  • output the name of the horse that has the highest average chance of success.

You can assume that each average will be different.

All outputs must have appropriate messages.

Save your program.

Copy and paste the program code into part 2(e)(ii) in the evidence document.

Test your program with the e following input data for fo
Height Risk
152 5
121 1
130 3
145 4

Take a screenshot of the output.

Save your program.

Copy and paste the screenshot into part 2(e)(iii) in the evidence document.

A computer program is designed to simulate horses doing show jumping. In show jumping, horses jump over obstacles called fences. A horse successfully jumps a fence if it does not knock the fence down. The program is written using Object-Oriented Programming (OOP). |The class Horse stores data about the horses.|| |---|---| |**`Horse`**|**`Horse`**| |`Name : STRING`<br>`MaxFenceHeight : INTEGER`<br>`PercentageSuccess : INTEGER`|stores the name given to the horse<br>stores the maximum height in cm that the horse can<br>jump, for example 132<br>stores the percentage chance of a horse not knocking<br>down a fence, for example 70 represents a 70% chance<br>of jumping a fence successfully| |`Constructor()`<br>`GetName()`<br>`GetMaxFenceHeight()`<br>`Success()`|initialises`Name`, `MaxFenceHeight` and<br>`PercentageSuccess` to its parameter values<br>returns the name of the horse<br>returns the maximum height the horse can jump<br>calculates and returns the percentage chance of a horse<br>successfully jumping a specific fence| **(a) (i)** Write program code to declare the class `Horse` and its constructor. <span class="part-marks">4 marks</span> Do **not** declare the other methods. Use your programming language’s appropriate constructor. All attributes must be private. If you are writing in Python, include attribute declarations using comments. Save your program as **Question2_N24** . Copy and paste the program code into part **2(a)(i)** in the evidence document. #### (ii) The get methods `GetName()` and `GetMaxFenceHeight()` each return the relevant attribute. <span class="part-marks">3 marks</span> Write program code for the get methods. Save your program. Copy and paste the program code into part **2(a)(ii)** in the evidence document. ### (b) The array `Horses` stores objects of type `Horse` . #### (i) The program has two horses: <span class="part-marks">5 marks</span> - The horse named ‘Beauty’ can jump a maximum height of 150 cm and has a success percentage rate of 72%. - The horse named ‘Jet’ can jump a maximum height of 160 cm and has a success percentage rate of 65%. Write program code to: - declare the array, `Horses`, local to the main program with space for **two** `Horse` objects - store the **two** horses described in the array - output the name of both `Horse` objects from the array. Save your program. Copy and paste the program code into part **2(b)(i)** in the evidence document. #### (ii) Test your program. <span class="part-marks">1 mark</span> Take a screenshot of the output. Save your program. Copy and paste the screenshot into part **2(b)(ii)** in the evidence document. ### (c) The class `Fence` stores data about the fences. Each fence has a height in cm and a risk number. |The risk is a whole number between 1 and 5 inclusive. A risk of 1 means the fence is the easiest type to jump. A risk of 5 means the fence is the hardest type to jump.|| |---|---| |**`Fence`**|**`Fence`**| |`Height : INTEGER`<br>`Risk : INTEGER`|stores the height of the fence in cm<br>the height is between 70 and 180 inclusive<br>stores the risk as a whole number between 1 and 5<br>inclusive| |`Constructor()`<br>`GetHeight()`<br>`GetRisk()`|initialises`Height` and`Risk` to its parameter values<br>returns the height of the fence<br>returns the risk of the fence| #### (i) Write program code to declare the class `Fence`, its constructor and get methods. <span class="part-marks">4 marks</span> Use your programming language’s appropriate constructor. All attributes must be private. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into part **2(c)(i)** in the evidence document. #### (ii) The array `Course` stores **four** `Fence` objects. The user inputs the height and risk for each fence, and these are validated before each fence is created. <span class="part-marks">5 marks</span> Amend the main program to: - declare the local array `Course` - take as input the data for **four** fences from the user - loop the input until both the height and risk are valid for each fence - create an instance of `Fence` for each of the **four** valid fences and store each instance in the array. Save your program. Copy and paste the program code into part **2(c)(ii)** in the evidence document. ### (d) The chance of a horse jumping a fence without knocking it down is calculated as follows. <span class="part-marks">5 marks</span> If the height of the fence is more than the maximum height a horse can jump, the success percentage is 20% of the horse’s `PercentageSuccess` . The risk does not affect this value. If the height of the fence is less than or equal to the maximum height a horse can jump, the risk gives a modifier value to multiply with the horse’s `PercentageSuccess` . The risk values and their modifiers are given in this table: |Risk|Modifier| |---|---| |5|0.6| |4|0.7| |3|0.8| |2|0.9| |1|1.0| For example: - The horse Jet has `PercentageSuccess` of 65 and `MaxFenceHeight` of 160. - A fence has a height of 140 and a risk of 3. - The height of the fence is less than the horse’s `MaxFenceHeight`, therefore the risk is used. - The risk of 3 gives the modifier 0.8. - The modifier 0.8 is multiplied by the horse’s `PercentageSuccess` of 65, which gives 52. - The chance of the horse successfully jumping this fence is 52%. The method `Success()` in the `Horse` class: - takes the height and risk of a fence as parameters - calculates the percentage chance of success for that horse jumping the fence without knocking it down - returns the calculated percentage chance of success as a real number. Write program code for `Success()` . Save your program. Copy and paste the program code into part **2(d)** in the evidence document. **(e) (i)** Write program code to amend the main program to: <span class="part-marks">3 marks</span> - calculate and output the chance of the first horse jumping each of the **four** fences without knocking each fence down - calculate and output the chance of the second horse jumping each of the **four** fences without knocking each fence down. All outputs must have appropriate messages including the name of the horse and the fence number. An example output for one horse jumping two fences is: ``` "The horse Fox at fence 1 has a 68% chance of success The horse Fox at fence 2 has a 72% chance of success" ``` Save your program. Copy and paste the program code into part **2(e)(i)** in the evidence document. #### (ii) Write program code to amend the main program to: <span class="part-marks">2 marks</span> <span class="part-marks">2 marks</span> - calculate and output the average chance of success for each horse jumping over all **four** fences without knocking each fence down (the average is the total of values divided by the quantity of values). An example output for one horse jumping all of the fences is: ``` "The horse Fox has an average 70% chance of jumping over all four fences" ``` - output the name of the horse that has the highest average chance of success. You can assume that each average will be different. All outputs must have appropriate messages. Save your program. Copy and paste the program code into part **2(e)(ii)** in the evidence document. |Test your program with the|e following input data for fo| |---|---| |**Height**|**Risk**| |152|5| |121|1| |130|3| |145|4| Take a screenshot of the output. Save your program. Copy and paste the screenshot into part **2(e)(iii)** in the evidence document.
Show mark scheme

2(a)(i)

Java class Horse{ private static String Name; private static Integer MaxFenceHeight; private static Integer PercentageSuccess; public Horse(String PName, Integer PMaxFenceHeight, Integer PPercentageSuccess){ Name = PName; MaxFenceHeight = PMaxFenceHeight; PercentageSuccess = PPercentageSuccess; } }

2(a)(ii)

Return MaxFenceHeight End Function Java public String GetName(){ return Name; } public Integer GetMaxFenceHeight(){ return MaxFenceHeight; }

2(b)(i)

Java Horse[] Horses = new Horse[2]; Horses[0] = new Horse("Beauty", 150, 72); Horses[1] = new Horse("Jet", 160, 65); System.out.println(Horses[0].GetName()); System.out.println(Horses[1].GetName());

2(b)(ii) [1 mark]

1 mark for both names output:

2(c)(i)

return Height; } public Integer GetRisk(){ return Risk; } }

2(c)(ii)

VB.NET Dim Course(5) As Fence Dim Height As Integer Dim Risk As Integer For x = 0 To 3 Do Console.WriteLine("Enter the height in cm") Height = Console.ReadLine() Loop Until Height >= 70 And Height <= 180 Do Console.WriteLine("Enter the risk between 1 (easy) and 5 (hard)") Risk = Console.ReadLine() Loop Until Risk >= 1 And Risk <= 5 Course(x) = New Fence(Height, Risk) Next Java Fence [] Course = new Fence [4]; for(Integer x = 0; x < 4; x++){ do { System.out.println("Enter the height in cm"); Height = Integer.parseInt(scanner.nextLine()); } while(Height <70 || Height > 180); do{ System.out.println("Enter the risk between 1 (easy) and 5 (hard)"); Risk = Integer.parseInt(scanner.nextLine()); }while(Risk <1 || Risk > 5); Course[x] = new Fence(Height, Risk); }

2(d)

Return PercentageSuccess ElseIf Risk = 2 Then Return PercentageSuccess * 0.9 ElseIf Risk = 3 Then Return PercentageSuccess * 0.8 ElseIf Risk = 4 Then Return PercentageSuccess * 0.7 Else Return PercentageSuccess * 0.6 End If End If End Function Java public static Double Success(Integer Height, Integer Risk){ if(Height > MaxFenceHeight){ return Double.valueOf(PercentageSuccess) * 0.2; }else{ if(Risk == 1){ return Double.valueOf(PercentageSuccess); }else if (Risk == 2){ return Double.valueOf(PercentageSuccess) * 0.9; }else if (Risk == 3){ return Double.valueOf(PercentageSuccess) * 0.8; }else if (Risk == 4){ return Double.valueOf(PercentageSuccess) * 0.7; }else{ return Double.valueOf(PercentageSuccess) * 0.6; } } }

2(e)(i) [3 marks]

1 mark each • Calling for each horse with the height and risk of all 4 fences … Success() • … using get methods for height and risk of each fence • … outputting the horse name, fence number and calculated success at fence in appropriate message e.g. Python for y in range(0, 2): for x in range(0, 4): Chance = Horses[y].Success(Course[x].GetHeight(), Course[x].GetRisk()) print(Horses[y].GetName(), "Fence", x + 1, "chance of success is", Chance, "%") VB.NET Dim Chance As Single For y = 0 To 1 For x = 0 To 3 Chance = Horses(y).Success(Course(x).GetHeight(), Course(x).GetRisk()) Console.WriteLine(Horses(y).GetName() & " Fence " & x + 1 & " chance of success is " & Chance & "%") Next Next Java Double Chance = 0.0; for(Integer y = 0; y < 2; y ++){ for(Integer x = 0; x < 4; x++){ Chance = Horses[y].Success(Course[x].GetHeight(), Course[x].GetRisk()); System.out.println(Horses[y].GetName() + " Fence " + (x + 1) + " chance of success is " + Chance + "%"); } }

2(e)(ii)

Java Double Total = 0.0; Double Chance = 0.0; Double Average = 0.0; for(Integer y = 0; y < 2; y ++){ Total = 0.0; for(Integer x = 0; x < 4; x++){ Chance = Horses[y].Success(Course[x].GetHeight(), Course[y].GetRisk()); System.out.println(Horses[y].GetName() + " Fence " + (x + 1) + " chance of success is " + Chance + "%"); Total = Total + Chance; } Average = Total / 4; AverageSuccess[y] = Average; System.out.println(Horses[y].GetName() + " average success rate is " + Average + "%"); } Double Highest = AverageSuccess[0]; Integer Winner = 0; for(Integer x = 1; x < 2; x++){ if(Highest < AverageSuccess[x]){ Winner = x; Highest = AverageSuccess[x]; } } System.out.println(Horses[Winner].GetName() + " has the highest average chance of success");

2(e)(iii) [2 marks]

1 mark each • Outputting showing correct input values for all fences, and correct chance for each horse on each jump • Outputs of average chance of each horse and horse name with highest average e.g.

Q1
Oct/Nov 2024 Paper 4 v2

A computer game is designed for users to select characters. Each character can take part in a group of events. Each group has five events. There are four types of event: jump, swim, run, drive.

The program is written using object-oriented programming.

) The class EventItem stores data about the events. EventItem
EventItem EventItem
EventName : STRING
Type : STRING
Difficulty : INTEGER
stores the name of the event
stores the type of event, either: jump, swim, run or drive
stores the difficulty of the event from 1 (easiest) to 5
(hardest)
Constructor()
GetName()
GetDifficulty()
GetEventType()
initialisesEventName, Type andDifficulty to its
parameter values
returns the name of the event
returns the difficulty of the event
returns the type of event

(i) Write program code to declare the class EventItem and its constructor. 4 marks

Do not declare the other methods.

Use your programming language’s appropriate constructor.

All attributes must be private.

If you are writing in Python, include attribute declarations, using comments.

Save your program as Question1_N24 .

Copy and paste the program code into part 1(a)(i) in the evidence document.

A computer game is designed for users to select characters. Each character can take part in a group of events. Each group has five events. There are four types of event: jump, swim, run, drive. The program is written using object-oriented programming. |) The class EventItem stores data about the events. EventItem|| |---|---| |**`EventItem`**|**`EventItem`**| |`EventName : STRING`<br>`Type : STRING`<br>`Difficulty : INTEGER`|stores the name of the event<br>stores the type of event, either: jump, swim, run or drive<br>stores the difficulty of the event from 1 (easiest) to 5<br>(hardest)| |`Constructor()`<br>`GetName()`<br>`GetDifficulty()`<br>`GetEventType()`|initialises`EventName`, `Type` and`Difficulty` to its<br>parameter values<br>returns the name of the event<br>returns the difficulty of the event<br>returns the type of event| #### (i) Write program code to declare the class `EventItem` and its constructor. <span class="part-marks">4 marks</span> Do **not** declare the other methods. Use your programming language’s appropriate constructor. All attributes must be private. If you are writing in Python, include attribute declarations, using comments. Save your program as **Question1_N24** . Copy and paste the program code into part **1(a)(i)** in the evidence document.
Show mark scheme

1(a)(i)

Java class EventItem{ private String EventName; private String EventType; private Integer Difficulty; public EventItem(String pName, String pType, Integer pDifficulty){ EventName= pName; EventType = pType; Difficulty = pDifficulty; } }

1(a)(ii)

VB.NET Function GetName() Return EventName End Function Function GetEventType() Return EventType End Function Function GetDifficulty() Return Difficulty End Function Java public String GetName(){ return EventName; } public String GetEventType(){ return EventType; } public Integer GetDifficulty(){ return Difficulty; }

1(b)(i) [1 mark]

1 mark each: • 1D array name with (min 5 elements and of type Group EventItem) e.g. Python Group = [] #type Event, 5 spaces VB.NET Dim Group(4) As EventItem Java EventItem[] Group = new EventItem[5];

1(b)(ii) [3 marks]

1 mark each • Any 1 instance of declared with values passed in correct order … EventItem • … stored in the array … Group • … remaining 4 correctly instantiated and stored in Group e.g. Python Group.append(EventItem("Bridge", "jump", 3)) Group.append(EventItem("Water wade", "swim", 4)) Group.append(EventItem("100 mile run", "run", 5)) Group.append(EventItem("Gridlock", "drive", 2)) Group.append(EventItem("Wall on wall", "jump", 4)) VB.NET Group(0) = New EventItem("Bridge", "jump", 3) Group(1) = New EventItem("Water wade", "swim", 4) Group(2) = New EventItem("100 mile run", "run", 5) Group(3) = New EventItem("Gridlock", "drive", 2) Group(4) = New EventItem("Wall on wall", "jump", 4) Java Group[0] = new EventItem("Bridge", "jump", 3); Group[1] = new EventItem("Water wade", "swim", 4); Group[2] = new EventItem("100 mile run", "run", 5); Group[3] = new EventItem("Gridlock", "drive", 2); Group[4] = new EventItem("Wall on wall", "jump", 4);

1(c)

Java class Character{ private String CName; private Integer Jump; private Integer Swim; private Integer Run; private Integer Drive; public Character(String pName, Integer pJump, Integer pSwim, Integer pRun, Integer pDrive){ CName= pName; Jump = pJump; Swim = pSwim; Run = pRun; Drive = pDrive; } public String GetName(){ return CName } }

1(d)

Java public Integer CalculateScore(String Type, Integer Difficulty){ Integer Chance = 0; Integer Difference = 0; if(Type.equals("jump")){ Chance = Jump; }else if(Type.equals("swim")){ Chance = Swim; }else if(Type.equals("run")){ Chance = Run; }else{ Chance = Drive; } if(Chance >= Difficulty){ return 100; }else{ Difference = Difficulty - Chance; if(Difference == 1){ return 80; }else if(Difference == 2){ return 60; }else if(Difference == 3){ return 40; }else if(Difference == 4){ return 20; } } }

1(e)(i) [2 marks]

1 mark each • Creating one new instance of with correct name and values for 1 character and storing Character • 2nd correct instance of and storing Character e.g. Python P1 = Character("Tarz", 5, 3, 5, 1) P2 = Character("Geni", 2, 2, 3, 4) VB.NET Dim P1 As Character = New Character("Tarz", 5, 3, 5, 1) Dim P2 As Character = New Character("Geni", 2, 2, 3, 4) Java Character P1 = new Character("Tarz", 5, 3, 5, 1); Character P2 = new Character("Geni", 2, 2, 3, 4);

1(e)(ii)

Java Integer P1Points = 0; Integer P2Points = 0; Integer P1EventScore = 0; Integer P2EventScore = 0; for(Integer x = 0; x < 5; x++){ P1EventScore = P1.CalculateScore(Group[x].GetEventType(), Group[x].GetDifficulty()); P2EventScore = P2.CalculateScore(Group[x].GetEventType(), Group[x].GetDifficulty()); System.out.println("P1 " + P1EventScore + " P2 " + P2EventScore); if(P1EventScore > P2EventScore){ P1Points++; System.out.println(P1.GetName() + " you win this event"); }else if(P2EventScore > P1EventScore){ P2Points++; System.out.println(P2.GetName() + " you win this event"); }else{ System.out.println("This event is a draw"); } } if(P1Points > P2Points){ System.out.println(P1.GetName() + " you have won with " + P1Points); }else if(P2Points > P1Points){ System.out.println(P2.GetName() + " you have won with " + P2Points); }else{ System.out.println("It's a draw"); }

1(e)(iii) [1 mark]

1 mark for output showing the correct winner for each event, the final winner’s name (and their points) e.g.

Q2
Oct/Nov 2024 Paper 4 v3

A computer program is designed to simulate horses doing show jumping. In show jumping, horses jump over obstacles called fences. A horse successfully jumps a fence if it does not knock the fence down.

The program is written using Object-Oriented Programming (OOP).

The class Horse stores data about the horses.
Horse Horse
Name : STRING
MaxFenceHeight : INTEGER
PercentageSuccess : INTEGER
stores the name given to the horse
stores the maximum height in cm that the horse can
jump, for example 132
stores the percentage chance of a horse not knocking
down a fence, for example 70 represents a 70% chance
of jumping a fence successfully
Constructor()
GetName()
GetMaxFenceHeight()
Success()
initialisesName, MaxFenceHeight and
PercentageSuccess to its parameter values
returns the name of the horse
returns the maximum height the horse can jump
calculates and returns the percentage chance of a horse
successfully jumping a specific fence

(a) (i) Write program code to declare the class Horse and its constructor. 4 marks

Do not declare the other methods.

Use your programming language’s appropriate constructor.

All attributes must be private. If you are writing in Python, include attribute declarations using comments.

Save your program as Question2_N24 .

Copy and paste the program code into part 2(a)(i) in the evidence document.

(ii) The get methods GetName() and GetMaxFenceHeight() each return the relevant attribute. 3 marks

Write program code for the get methods.

Save your program.

Copy and paste the program code into part 2(a)(ii) in the evidence document.

(b) The array Horses stores objects of type Horse .

(i) The program has two horses: 5 marks

  • The horse named ‘Beauty’ can jump a maximum height of 150 cm and has a success percentage rate of 72%.

  • The horse named ‘Jet’ can jump a maximum height of 160 cm and has a success percentage rate of 65%.

Write program code to:

  • declare the array, Horses, local to the main program with space for two Horse objects

  • store the two horses described in the array

  • output the name of both Horse objects from the array.

Save your program.

Copy and paste the program code into part 2(b)(i) in the evidence document.

(ii) Test your program. 1 mark

Take a screenshot of the output.

Save your program.

Copy and paste the screenshot into part 2(b)(ii) in the evidence document.

(c) The class Fence stores data about the fences. Each fence has a height in cm and a risk number.

The risk is a whole number between 1 and 5 inclusive. A risk of 1 means the fence is the easiest type to jump. A risk of 5 means the fence is the hardest type to jump.
Fence Fence
Height : INTEGER
Risk : INTEGER
stores the height of the fence in cm
the height is between 70 and 180 inclusive
stores the risk as a whole number between 1 and 5
inclusive
Constructor()
GetHeight()
GetRisk()
initialisesHeight andRisk to its parameter values
returns the height of the fence
returns the risk of the fence

(i) Write program code to declare the class Fence, its constructor and get methods. 4 marks

Use your programming language’s appropriate constructor.

All attributes must be private.

If you are writing in Python, include attribute declarations using comments.

Save your program.

Copy and paste the program code into part 2(c)(i) in the evidence document.

(ii) The array Course stores four Fence objects. The user inputs the height and risk for each fence, and these are validated before each fence is created. 5 marks

Amend the main program to:

  • declare the local array Course

  • take as input the data for four fences from the user

  • loop the input until both the height and risk are valid for each fence

  • create an instance of Fence for each of the four valid fences and store each instance in the array.

Save your program.

Copy and paste the program code into part 2(c)(ii) in the evidence document.

(d) The chance of a horse jumping a fence without knocking it down is calculated as follows. 5 marks

If the height of the fence is more than the maximum height a horse can jump, the success percentage is 20% of the horse’s PercentageSuccess . The risk does not affect this value.

If the height of the fence is less than or equal to the maximum height a horse can jump, the risk gives a modifier value to multiply with the horse’s PercentageSuccess .

The risk values and their modifiers are given in this table:

Risk Modifier
5 0.6
4 0.7
3 0.8
2 0.9
1 1.0

For example:

  • The horse Jet has PercentageSuccess of 65 and MaxFenceHeight of 160.

  • A fence has a height of 140 and a risk of 3.

  • The height of the fence is less than the horse’s MaxFenceHeight, therefore the risk is used.

  • The risk of 3 gives the modifier 0.8.

  • The modifier 0.8 is multiplied by the horse’s PercentageSuccess of 65, which gives 52.

  • The chance of the horse successfully jumping this fence is 52%.

The method Success() in the Horse class:

  • takes the height and risk of a fence as parameters

  • calculates the percentage chance of success for that horse jumping the fence without knocking it down

  • returns the calculated percentage chance of success as a real number.

Write program code for Success() .

Save your program.

Copy and paste the program code into part 2(d) in the evidence document. (e) (i) Write program code to amend the main program to: 3 marks

  • calculate and output the chance of the first horse jumping each of the four fences without knocking each fence down

  • calculate and output the chance of the second horse jumping each of the four fences without knocking each fence down.

All outputs must have appropriate messages including the name of the horse and the fence number.

An example output for one horse jumping two fences is:

     "The horse Fox at fence 1 has a 68% chance of success
     The horse Fox at fence 2 has a 72% chance of success"

Save your program.

Copy and paste the program code into part 2(e)(i) in the evidence document.

(ii) Write program code to amend the main program to: 2 marks 2 marks

  • calculate and output the average chance of success for each horse jumping over all four fences without knocking each fence down (the average is the total of values divided by the quantity of values). An example output for one horse jumping all of the fences is:
      "The horse Fox has an average 70% chance of jumping over all four
      fences"
  • output the name of the horse that has the highest average chance of success.

You can assume that each average will be different.

All outputs must have appropriate messages.

Save your program.

Copy and paste the program code into part 2(e)(ii) in the evidence document.

Test your program with the e following input data for fo
Height Risk
152 5
121 1
130 3
145 4

Take a screenshot of the output.

Save your program.

Copy and paste the screenshot into part 2(e)(iii) in the evidence document.

A computer program is designed to simulate horses doing show jumping. In show jumping, horses jump over obstacles called fences. A horse successfully jumps a fence if it does not knock the fence down. The program is written using Object-Oriented Programming (OOP). |The class Horse stores data about the horses.|| |---|---| |**`Horse`**|**`Horse`**| |`Name : STRING`<br>`MaxFenceHeight : INTEGER`<br>`PercentageSuccess : INTEGER`|stores the name given to the horse<br>stores the maximum height in cm that the horse can<br>jump, for example 132<br>stores the percentage chance of a horse not knocking<br>down a fence, for example 70 represents a 70% chance<br>of jumping a fence successfully| |`Constructor()`<br>`GetName()`<br>`GetMaxFenceHeight()`<br>`Success()`|initialises`Name`, `MaxFenceHeight` and<br>`PercentageSuccess` to its parameter values<br>returns the name of the horse<br>returns the maximum height the horse can jump<br>calculates and returns the percentage chance of a horse<br>successfully jumping a specific fence| **(a) (i)** Write program code to declare the class `Horse` and its constructor. <span class="part-marks">4 marks</span> Do **not** declare the other methods. Use your programming language’s appropriate constructor. All attributes must be private. If you are writing in Python, include attribute declarations using comments. Save your program as **Question2_N24** . Copy and paste the program code into part **2(a)(i)** in the evidence document. #### (ii) The get methods `GetName()` and `GetMaxFenceHeight()` each return the relevant attribute. <span class="part-marks">3 marks</span> Write program code for the get methods. Save your program. Copy and paste the program code into part **2(a)(ii)** in the evidence document. ### (b) The array `Horses` stores objects of type `Horse` . #### (i) The program has two horses: <span class="part-marks">5 marks</span> - The horse named ‘Beauty’ can jump a maximum height of 150 cm and has a success percentage rate of 72%. - The horse named ‘Jet’ can jump a maximum height of 160 cm and has a success percentage rate of 65%. Write program code to: - declare the array, `Horses`, local to the main program with space for **two** `Horse` objects - store the **two** horses described in the array - output the name of both `Horse` objects from the array. Save your program. Copy and paste the program code into part **2(b)(i)** in the evidence document. #### (ii) Test your program. <span class="part-marks">1 mark</span> Take a screenshot of the output. Save your program. Copy and paste the screenshot into part **2(b)(ii)** in the evidence document. ### (c) The class `Fence` stores data about the fences. Each fence has a height in cm and a risk number. |The risk is a whole number between 1 and 5 inclusive. A risk of 1 means the fence is the easiest type to jump. A risk of 5 means the fence is the hardest type to jump.|| |---|---| |**`Fence`**|**`Fence`**| |`Height : INTEGER`<br>`Risk : INTEGER`|stores the height of the fence in cm<br>the height is between 70 and 180 inclusive<br>stores the risk as a whole number between 1 and 5<br>inclusive| |`Constructor()`<br>`GetHeight()`<br>`GetRisk()`|initialises`Height` and`Risk` to its parameter values<br>returns the height of the fence<br>returns the risk of the fence| #### (i) Write program code to declare the class `Fence`, its constructor and get methods. <span class="part-marks">4 marks</span> Use your programming language’s appropriate constructor. All attributes must be private. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into part **2(c)(i)** in the evidence document. #### (ii) The array `Course` stores **four** `Fence` objects. The user inputs the height and risk for each fence, and these are validated before each fence is created. <span class="part-marks">5 marks</span> Amend the main program to: - declare the local array `Course` - take as input the data for **four** fences from the user - loop the input until both the height and risk are valid for each fence - create an instance of `Fence` for each of the **four** valid fences and store each instance in the array. Save your program. Copy and paste the program code into part **2(c)(ii)** in the evidence document. ### (d) The chance of a horse jumping a fence without knocking it down is calculated as follows. <span class="part-marks">5 marks</span> If the height of the fence is more than the maximum height a horse can jump, the success percentage is 20% of the horse’s `PercentageSuccess` . The risk does not affect this value. If the height of the fence is less than or equal to the maximum height a horse can jump, the risk gives a modifier value to multiply with the horse’s `PercentageSuccess` . The risk values and their modifiers are given in this table: |Risk|Modifier| |---|---| |5|0.6| |4|0.7| |3|0.8| |2|0.9| |1|1.0| For example: - The horse Jet has `PercentageSuccess` of 65 and `MaxFenceHeight` of 160. - A fence has a height of 140 and a risk of 3. - The height of the fence is less than the horse’s `MaxFenceHeight`, therefore the risk is used. - The risk of 3 gives the modifier 0.8. - The modifier 0.8 is multiplied by the horse’s `PercentageSuccess` of 65, which gives 52. - The chance of the horse successfully jumping this fence is 52%. The method `Success()` in the `Horse` class: - takes the height and risk of a fence as parameters - calculates the percentage chance of success for that horse jumping the fence without knocking it down - returns the calculated percentage chance of success as a real number. Write program code for `Success()` . Save your program. Copy and paste the program code into part **2(d)** in the evidence document. **(e) (i)** Write program code to amend the main program to: <span class="part-marks">3 marks</span> - calculate and output the chance of the first horse jumping each of the **four** fences without knocking each fence down - calculate and output the chance of the second horse jumping each of the **four** fences without knocking each fence down. All outputs must have appropriate messages including the name of the horse and the fence number. An example output for one horse jumping two fences is: ``` "The horse Fox at fence 1 has a 68% chance of success The horse Fox at fence 2 has a 72% chance of success" ``` Save your program. Copy and paste the program code into part **2(e)(i)** in the evidence document. #### (ii) Write program code to amend the main program to: <span class="part-marks">2 marks</span> <span class="part-marks">2 marks</span> - calculate and output the average chance of success for each horse jumping over all **four** fences without knocking each fence down (the average is the total of values divided by the quantity of values). An example output for one horse jumping all of the fences is: ``` "The horse Fox has an average 70% chance of jumping over all four fences" ``` - output the name of the horse that has the highest average chance of success. You can assume that each average will be different. All outputs must have appropriate messages. Save your program. Copy and paste the program code into part **2(e)(ii)** in the evidence document. |Test your program with the|e following input data for fo| |---|---| |**Height**|**Risk**| |152|5| |121|1| |130|3| |145|4| Take a screenshot of the output. Save your program. Copy and paste the screenshot into part **2(e)(iii)** in the evidence document.
Show mark scheme

2(a)(i)

Java class Horse{ private static String Name; private static Integer MaxFenceHeight; private static Integer PercentageSuccess; public Horse(String PName, Integer PMaxFenceHeight, Integer PPercentageSuccess){ Name = PName; MaxFenceHeight = PMaxFenceHeight; PercentageSuccess = PPercentageSuccess; } }

2(a)(ii)

Return MaxFenceHeight End Function Java public String GetName(){ return Name; } public Integer GetMaxFenceHeight(){ return MaxFenceHeight; }

2(b)(i)

Java Horse[] Horses = new Horse[2]; Horses[0] = new Horse("Beauty", 150, 72); Horses[1] = new Horse("Jet", 160, 65); System.out.println(Horses[0].GetName()); System.out.println(Horses[1].GetName());

2(b)(ii) [1 mark]

1 mark for both names output:

2(c)(i)

return Height; } public Integer GetRisk(){ return Risk; } }

2(c)(ii)

VB.NET Dim Course(5) As Fence Dim Height As Integer Dim Risk As Integer For x = 0 To 3 Do Console.WriteLine("Enter the height in cm") Height = Console.ReadLine() Loop Until Height >= 70 And Height <= 180 Do Console.WriteLine("Enter the risk between 1 (easy) and 5 (hard)") Risk = Console.ReadLine() Loop Until Risk >= 1 And Risk <= 5 Course(x) = New Fence(Height, Risk) Next Java Fence [] Course = new Fence [4]; for(Integer x = 0; x < 4; x++){ do { System.out.println("Enter the height in cm"); Height = Integer.parseInt(scanner.nextLine()); } while(Height <70 || Height > 180); do{ System.out.println("Enter the risk between 1 (easy) and 5 (hard)"); Risk = Integer.parseInt(scanner.nextLine()); }while(Risk <1 || Risk > 5); Course[x] = new Fence(Height, Risk); }

2(d)

Return PercentageSuccess ElseIf Risk = 2 Then Return PercentageSuccess * 0.9 ElseIf Risk = 3 Then Return PercentageSuccess * 0.8 ElseIf Risk = 4 Then Return PercentageSuccess * 0.7 Else Return PercentageSuccess * 0.6 End If End If End Function Java public static Double Success(Integer Height, Integer Risk){ if(Height > MaxFenceHeight){ return Double.valueOf(PercentageSuccess) * 0.2; }else{ if(Risk == 1){ return Double.valueOf(PercentageSuccess); }else if (Risk == 2){ return Double.valueOf(PercentageSuccess) * 0.9; }else if (Risk == 3){ return Double.valueOf(PercentageSuccess) * 0.8; }else if (Risk == 4){ return Double.valueOf(PercentageSuccess) * 0.7; }else{ return Double.valueOf(PercentageSuccess) * 0.6; } } }

2(e)(i) [3 marks]

1 mark each • Calling for each horse with the height and risk of all 4 fences … Success() • … using get methods for height and risk of each fence • … outputting the horse name, fence number and calculated success at fence in appropriate message e.g. Python for y in range(0, 2): for x in range(0, 4): Chance = Horses[y].Success(Course[x].GetHeight(), Course[x].GetRisk()) print(Horses[y].GetName(), "Fence", x + 1, "chance of success is", Chance, "%") VB.NET Dim Chance As Single For y = 0 To 1 For x = 0 To 3 Chance = Horses(y).Success(Course(x).GetHeight(), Course(x).GetRisk()) Console.WriteLine(Horses(y).GetName() & " Fence " & x + 1 & " chance of success is " & Chance & "%") Next Next Java Double Chance = 0.0; for(Integer y = 0; y < 2; y ++){ for(Integer x = 0; x < 4; x++){ Chance = Horses[y].Success(Course[x].GetHeight(), Course[x].GetRisk()); System.out.println(Horses[y].GetName() + " Fence " + (x + 1) + " chance of success is " + Chance + "%"); } }

2(e)(ii)

Java Double Total = 0.0; Double Chance = 0.0; Double Average = 0.0; for(Integer y = 0; y < 2; y ++){ Total = 0.0; for(Integer x = 0; x < 4; x++){ Chance = Horses[y].Success(Course[x].GetHeight(), Course[y].GetRisk()); System.out.println(Horses[y].GetName() + " Fence " + (x + 1) + " chance of success is " + Chance + "%"); Total = Total + Chance; } Average = Total / 4; AverageSuccess[y] = Average; System.out.println(Horses[y].GetName() + " average success rate is " + Average + "%"); } Double Highest = AverageSuccess[0]; Integer Winner = 0; for(Integer x = 1; x < 2; x++){ if(Highest < AverageSuccess[x]){ Winner = x; Highest = AverageSuccess[x]; } } System.out.println(Horses[Winner].GetName() + " has the highest average chance of success");

2(e)(iii) [2 marks]

1 mark each • Outputting showing correct input values for all fences, and correct chance for each horse on each jump • Outputs of average chance of each horse and horse name with highest average e.g.

Q8
May/Jun 2024 Paper 3 v1

A declarative programming language is used to represent the features that are available and the features that are unavailable on different body styles of a car.

  01 feature(sunroof).
  02 feature(automatic_tailgate).
  03 feature(heated_seats).
  04 feature(extra_seats).
  05 feature(reversing_camera).
  06 feature(dashboard_camera).
  07 feature(air_conditioning).
  08 feature(heated_windscreen).
  09 feature(satnav).
  10 bodystyle(saloon).
  11 bodystyle(hatchback).
  12 bodystyle(estate).
  13 bodystyle(minivan).
  14 bodystyle(convertible).
  15 available(sunroof, hatchback).
  16 available(sunroof, minivan).
  17 available(reversing_camera, hatchback).
  18 available(extra_seats, minivan).
  19 available(reversing_camera, saloon).
  20 unavailable(sunroof, convertible).
  21 unavailable(automatic_tailgate, saloon).
  22 unavailable(extra_seats, hatchback).

These clauses have the meanings:

Clause Meaning
01 Sunroof is a feature.
10 Saloon is a body style.
15 Sunroof is available on a hatchback.
20 Sunroof is unavailable on a convertible.

(a) Sliding doors is a feature that is available on a minivan but unavailable on a hatchback. 3 marks

Write additional clauses to represent this information.

23

24

25

A **declarative** programming language is used to represent the features that are available and the features that are unavailable on different body styles of a car. ``` 01 feature(sunroof). 02 feature(automatic_tailgate). 03 feature(heated_seats). 04 feature(extra_seats). 05 feature(reversing_camera). 06 feature(dashboard_camera). 07 feature(air_conditioning). 08 feature(heated_windscreen). 09 feature(satnav). 10 bodystyle(saloon). 11 bodystyle(hatchback). 12 bodystyle(estate). 13 bodystyle(minivan). 14 bodystyle(convertible). 15 available(sunroof, hatchback). 16 available(sunroof, minivan). 17 available(reversing_camera, hatchback). 18 available(extra_seats, minivan). 19 available(reversing_camera, saloon). 20 unavailable(sunroof, convertible). 21 unavailable(automatic_tailgate, saloon). 22 unavailable(extra_seats, hatchback). ``` These clauses have the meanings: |Clause|Meaning| |---|---| |`01`|Sunroof is a feature.| |`10`|Saloon is a body style.| |`15`|Sunroof is available on a hatchback.| |`20`|Sunroof is unavailable on a convertible.| ### (a) Sliding doors is a feature that is available on a minivan but unavailable on a hatchback. <span class="part-marks">3 marks</span> Write additional clauses to represent this information. `23` `24` `25`
Show mark scheme

8(a) [3 marks]

mark for each correctly completed clause ( Max 3 ) (23) feature(sliding_doors). (24) available(sliding_doors, minivan). (25) unavailable(sliding_doors, hatchback).

8(b) [1 mark]

(Options =) sunroof, reversing_camera

8(c) [4 marks]

mark per mark point ( Max 4 ) feature(F) bodystyle(B) unavailable(F, B) all correct Boolean operators and punctuation (allow , for AND) and no additional lines of code Example answers may_choose_option(F, B) feature(F) AND bodystyle(B) AND NOT unavailable(F, B). feature(F), bodystyle(B), NOT unavailable(F, B).

Q10
May/Jun 2024 Paper 3 v2

A declarative programming language is used to allow clients to choose daily activities at the beach.

  01 activity(paddleboarding).
  02 activity(sailing).
  03 activity(rowing).
  04 activity(kayaking).
  05 activity(jetskiing).
  06 client(stevie).
  07 client(antonio).
  08 client(henry).
  09 client(eliza).
  10 client(rebeka).
  11 client(danny).
  12 client(erik).
  13 client(simone).
  14 client(petra).
  15 client(frankie).
  16 choice(petra, rowing).
  17 choice(frankie, sailing).
  18 choice(erik, sailing).
  19 choice(eliza, rowing).
  20 choice(stevie, jetskiing).
  21 choice(henry, sailing).
  22 done(henry, jetskiing).
  23 done(rebeka, jetskiing).
  24 done(antonio, kayaking).

These clauses have the meanings:

Clause Meaning
01 Paddle boarding is an activity.
06 Stevie is a client.
16 Petra has chosen rowing.
22 Henry has already done jet skiing.

(a) Jane is a client who would like to choose the activity surfing and she has already done sailing. 4 marks

Write additional clauses to represent this information.

25

26

27

28

(b) Using the variable List, the goal:

       choice(List, rowing)

returns

       List = petra, eliza

Write the result returned by the goal:

       choice(List, sailing)

List = [1]

(c) C is a client who would like to choose A if A is an activity and C has not already done A . 4 marks

Write this as a rule:

    may_choose_activity(C, A)

IF

A **declarative** programming language is used to allow clients to choose daily activities at the beach. ``` 01 activity(paddleboarding). 02 activity(sailing). 03 activity(rowing). 04 activity(kayaking). 05 activity(jetskiing). 06 client(stevie). 07 client(antonio). 08 client(henry). 09 client(eliza). 10 client(rebeka). 11 client(danny). 12 client(erik). 13 client(simone). 14 client(petra). 15 client(frankie). 16 choice(petra, rowing). 17 choice(frankie, sailing). 18 choice(erik, sailing). 19 choice(eliza, rowing). 20 choice(stevie, jetskiing). 21 choice(henry, sailing). 22 done(henry, jetskiing). 23 done(rebeka, jetskiing). 24 done(antonio, kayaking). ``` These clauses have the meanings: |Clause|Meaning| |---|---| |`01`|Paddle boarding is an activity.| |`06`|Stevie is a client.| |`16`|Petra has chosen rowing.| |`22`|Henry has already done jet skiing.| ### (a) Jane is a client who would like to choose the activity surfing and she has already done sailing. <span class="part-marks">4 marks</span> Write additional clauses to represent this information. `25` `26` `27` `28` ### (b) Using the variable `List`, the goal: ``` choice(List, rowing) ``` returns ``` List = petra, eliza ``` Write the result returned by the goal: ``` choice(List, sailing) ``` `List =` [1] ### (c) `C` is a client who would like to choose `A` if `A` is an activity and `C` has **not** already done `A` . <span class="part-marks">4 marks</span> Write this as a rule: ``` may_choose_activity(C, A) ``` `IF`
Show mark scheme

10(a) [4 marks]

mark for each correctly completed clause ( Max 4 ) Example answer (25) client(jane). (26) activity(surfing). (27) choice(jane, surfing). (28) done(jane, sailing).

10(b) [1 mark]

(List =) frankie, erik, henry

10(c) [4 marks]

mark per mark point ( Max 4 ) client(C) activity(A) done(C, A) all correct Boolean operators and punctuation (allow , for AND). There must be the correct number of terms and no additional lines of code Example answers may_choose_activity(C, A) client(C) AND activity(A) AND NOT done(C, A). client(C), activity(A), NOT (done(C, A)).

Q8
May/Jun 2024 Paper 3 v3

A declarative programming language is used to represent the features that are available and the features that are unavailable on different body styles of a car.

01 feature(sunroof). 02 feature(automatic_tailgate). 03 feature(heated_seats). 04 feature(extra_seats). 05 feature(reversing_camera). 06 feature(dashboard_camera). 07 feature(air_conditioning). 08 feature(heated_windscreen). 09 feature(satnav). 10 bodystyle(saloon). 11 bodystyle(hatchback). 12 bodystyle(estate). 13 bodystyle(minivan). 14 bodystyle(convertible). 15 available(sunroof, hatchback). 16 available(sunroof, minivan). 17 available(reversing_camera, hatchback). 18 available(extra_seats, minivan). 19 available(reversing_camera, saloon). 20 unavailable(sunroof, convertible). 21 unavailable(automatic_tailgate, saloon). 22 unavailable(extra_seats, hatchback).

These clauses have the meanings:

Clause Meaning
01 Sunroof is a feature.
10 Saloon is a body style.
15 Sunroof is available on a hatchback.
20 Sunroof is unavailable on a convertible.

(a) Sliding doors is a feature that is available on a minivan but unavailable on a hatchback. 3 marks

Write additional clauses to represent this information.

23

24

25

(b) Using the variable Options, the goal:

available(Options, saloon)

returns

Options = reversing_camera

Write the result returned by the goal:

A **declarative** programming language is used to represent the features that are available and the features that are unavailable on different body styles of a car. 01 feature(sunroof). 02 feature(automatic_tailgate). 03 feature(heated_seats). 04 feature(extra_seats). 05 feature(reversing_camera). 06 feature(dashboard_camera). 07 feature(air_conditioning). 08 feature(heated_windscreen). 09 feature(satnav). 10 bodystyle(saloon). 11 bodystyle(hatchback). 12 bodystyle(estate). 13 bodystyle(minivan). 14 bodystyle(convertible). 15 available(sunroof, hatchback). 16 available(sunroof, minivan). 17 available(reversing_camera, hatchback). 18 available(extra_seats, minivan). 19 available(reversing_camera, saloon). 20 unavailable(sunroof, convertible). 21 unavailable(automatic_tailgate, saloon). 22 unavailable(extra_seats, hatchback). These clauses have the meanings: |Clause|Meaning| |---|---| |01|Sunroof is a feature.| |10|Saloon is a body style.| |15|Sunroof is available on a hatchback.| |20|Sunroof is unavailable on a convertible.| ### (a) Sliding doors is a feature that is available on a minivan but unavailable on a hatchback. <span class="part-marks">3 marks</span> Write additional clauses to represent this information. 23 24 25 ### (b) Using the variable Options, the goal: available(Options, saloon) returns Options = reversing_camera Write the result returned by the goal:
Show mark scheme

8(a) [3 marks]

mark for each correctly completed clause ( Max 3 ) (23) feature(sliding_doors). (24) available(sliding_doors, minivan). (25) unavailable(sliding_doors, hatchback).

8(b) [1 mark]

(Options =) sunroof, reversing_camera

8(c) [4 marks]

mark per mark point ( Max 4 ) feature(F) bodystyle(B) unavailable(F, B) all correct Boolean operators and punctuation (allow , for AND) and no additional lines of code Example answers may_choose_option(F, B) feature(F) AND bodystyle(B) AND NOT unavailable(F, B). feature(F), bodystyle(B), NOT unavailable(F, B).

Q2
May/Jun 2024 Paper 4 v1

A computer program will store data about trees.

The user can enter their requirements for a tree and a suitable tree will be selected.

The program is written using object‑oriented programming.

The class Tree stores data about the trees. Tree
Tree Tree
TreeName : STRING
HeightGrowth : INTEGER
MaxHeight : INTEGER
MaxWidth : INTEGER
Evergreen : STRING
stores the name of the tree
stores the number of cm the tree will grow each year
stores the maximum height in cm that the tree will grow
stores the maximum width in cm that the tree will grow
stores whether the tree keeps its leaves as"Yes", or
loses its leaves as"No"
Constructor()
GetTreeName()
GetGrowth()
GetMaxHeight()
GetMaxWidth()
GetEvergreen()
initialisesTreeName, HeightGrowth, MaxHeight,
MaxWidth andEvergreen to its parameter values
returns the name of the tree
returns the number of cm the tree will grow each year
returns the maximum height in cm that the tree will grow
returns the maximum width in cm that the tree will grow
returns whether the tree keeps its leaves or loses its
leaves

(a) (i) Write program code to declare the class Tree and its constructor. 4 marks

Do not declare the other methods.

Use the appropriate constructor for your programming language.

All attributes must be private.

If you are writing in Python, include attribute declarations using comments.

Save your program as Question2_J24 .

Copy and paste the program code into part 2(a)(i) in the evidence document.

(ii) The get methods GetTreeName(), GetGrowth(), GetMaxHeight(), GetMaxWidth() and GetEvergreen() each return the relevant attribute. 3 marks

Write program code for the get methods.

Save your program.

Copy and paste the program code into part 2(a)(ii) in the evidence document.

(b) The text file Trees.txt stores data about 9 trees. 7 marks

The data in the file is stored in the format:

Tree name,Height growth each year,Maximum height,Maximum width,Evergreen

For example, the first row of data is:

Beech,30,400,200,No

The tree is a Beech. It can grow 30 cm each year. It has a maximum height of 400 cm. It has a maximum width of 200 cm. It is not evergreen (it loses its leaves).

The function ReadData() :

  • creates an array of type Tree

  • reads the data from the file

  • raises an exception if the file is not found

  • creates a new object of type Tree for each tree in the file

  • appends each object to the array

  • returns the array.

Write program code for ReadData() .

Save your program.

Copy and paste the program code into part 2(b) in the evidence document.

(c) The procedure PrintTrees() takes a Tree object as a parameter and outputs the tree’s name, height growth each year, maximum height, maximum width and whether it is evergreen. 4 marks

The output message changes depending on whether it is evergreen.

If it is evergreen, it is in the format:

TreeName has a maximum height MaxHeight a maximum width MaxWidth and grows HeightGrowth cm a year. It does not lose its leaves.

If it is not evergreen, it is in the format:

TreeName has a maximum height MaxHeight a maximum width MaxWidth and grows HeightGrowth cm a year. It loses its leaves each year.

Write program code for PrintTrees() .

Save your program.

Copy and paste the program code into part 2(c) in the evidence document.

(d) The main program calls ReadData(), stores the return value and calls PrintTrees() with the first object in the returned array.

(i) Write program code for the main program. 2 marks

Save your program.

Copy and paste the program code into part 2(d)(i) in the evidence document.

(ii) Test your program. 1 mark

Take a screenshot of the output(s).

Save your program.

Copy and paste the screenshot into part 2(d)(ii) in the evidence document.

(e) The procedure ChooseTree() takes an array of Tree objects as a parameter.

The procedure prompts the user to input their requirements for a tree. The user needs to enter:

  • the maximum height the tree can be in cm

  • the maximum width the tree can be in cm

  • whether they want the tree to be evergreen, or not evergreen.

A tree meets the requirements if:

  • the tree’s maximum height is not more than the user’s input

and

  • the tree’s maximum width is not more than the user’s input

and

  • the tree matches their evergreen input.

The procedure creates a new array of all the Tree objects that meet all the requirements.

The procedure calls PrintTrees() for each Tree object that meets all the requirements. If there are no trees that meet all the requirements, a suitable message is output.

(i) Write program code for ChooseTree() . 6 marks

Save your program.

Copy and paste the program code into part 2(e)(i) in the evidence document.

(ii) The procedure ChooseTree() needs amending. After the procedure has output the list of trees that meet all the requirements, the procedure needs to: 2 marks

  • take as input the name of one of the trees that the user would like to buy from those that meet all the requirements

  • take as input the height of the tree in cm when it is bought

  • calculate and output how many years it will take the tree to grow to its maximum height.

For example, the user inputs the tree, Beech. The tree’s height is 40 cm when bought. The tree will take 12 years to reach its maximum height of 400 cm.

Write program code to amend ChooseTree() .

Save your program.

Copy and paste the program code into part 2(e)(ii) in the evidence document.

(iii) Write program code to amend the main program to call ChooseTrees() . 2 marks

Test your program with the following tree requirements:

  • a maximum height of 400 cm

  • a maximum width of 200 cm

  • a tree that is evergreen (does not lose its leaves).

When asked for the tree selection, use the following data:

  • first tree name entered is ‘Blue Conifer’

  • starting height is 100 cm.

Take a screenshot of the outputs.

Save your program.

Copy and paste the screenshot into part 2(e)(iii) in the evidence document.

A computer program will store data about trees. The user can enter their requirements for a tree and a suitable tree will be selected. The program is written using object‑oriented programming. |The class Tree stores data about the trees. Tree|| |---|---| |**`Tree`**|**`Tree`**| |`TreeName : STRING`<br>`HeightGrowth : INTEGER`<br>`MaxHeight : INTEGER`<br>`MaxWidth : INTEGER`<br>`Evergreen : STRING`|stores the name of the tree<br>stores the number of cm the tree will grow each year<br>stores the maximum height in cm that the tree will grow<br>stores the maximum width in cm that the tree will grow<br>stores whether the tree keeps its leaves as`"Yes"`, or<br>loses its leaves as`"No"`| |`Constructor()`<br>`GetTreeName()`<br>`GetGrowth()`<br>`GetMaxHeight()`<br>`GetMaxWidth()`<br>`GetEvergreen()`|initialises`TreeName`, `HeightGrowth`, `MaxHeight`, <br>`MaxWidth` and`Evergreen` to its parameter values<br>returns the name of the tree<br>returns the number of cm the tree will grow each year<br>returns the maximum height in cm that the tree will grow<br>returns the maximum width in cm that the tree will grow<br>returns whether the tree keeps its leaves or loses its<br>leaves| **(a) (i)** Write program code to declare the class `Tree` and its constructor. <span class="part-marks">4 marks</span> Do **not** declare the other methods. Use the appropriate constructor for your programming language. All attributes must be private. If you are writing in Python, include attribute declarations using comments. Save your program as **Question2_J24** . Copy and paste the program code into part **2(a)(i)** in the evidence document. #### (ii) The get methods `GetTreeName()`, `GetGrowth()`, `GetMaxHeight()`, `GetMaxWidth()` and `GetEvergreen()` each return the relevant attribute. <span class="part-marks">3 marks</span> Write program code for the get methods. Save your program. Copy and paste the program code into part **2(a)(ii)** in the evidence document. ### (b) The text file `Trees.txt` stores data about 9 trees. <span class="part-marks">7 marks</span> The data in the file is stored in the format: Tree name,Height growth each year,Maximum height,Maximum width,Evergreen For example, the first row of data is: Beech,30,400,200,No The tree is a Beech. It can grow 30 cm each year. It has a maximum height of 400 cm. It has a maximum width of 200 cm. It is **not** evergreen (it loses its leaves). The function `ReadData()` : - creates an array of type `Tree` - reads the data from the file - raises an exception if the file is **not** found - creates a new object of type `Tree` for each tree in the file - appends each object to the array - returns the array. Write program code for `ReadData()` . Save your program. Copy and paste the program code into part **2(b)** in the evidence document. ### (c) The procedure `PrintTrees()` takes a `Tree` object as a parameter and outputs the tree’s name, height growth each year, maximum height, maximum width and whether it is evergreen. <span class="part-marks">4 marks</span> The output message changes depending on whether it is evergreen. If it is evergreen, it is in the format: `TreeName` has a maximum height `MaxHeight` a maximum width `MaxWidth` and grows `HeightGrowth` cm a year. It does not lose its leaves. If it is **not** evergreen, it is in the format: `TreeName` has a maximum height `MaxHeight` a maximum width `MaxWidth` and grows `HeightGrowth` cm a year. It loses its leaves each year. Write program code for `PrintTrees()` . Save your program. Copy and paste the program code into part **2(c)** in the evidence document. ### (d) The main program calls `ReadData()`, stores the return value and calls `PrintTrees()` with the first object in the returned array. #### (i) Write program code for the main program. <span class="part-marks">2 marks</span> Save your program. Copy and paste the program code into part **2(d)(i)** in the evidence document. #### (ii) Test your program. <span class="part-marks">1 mark</span> Take a screenshot of the output(s). Save your program. Copy and paste the screenshot into part **2(d)(ii)** in the evidence document. ### (e) The procedure `ChooseTree()` takes an array of `Tree` objects as a parameter. The procedure prompts the user to input their requirements for a tree. The user needs to enter: - the maximum height the tree can be in cm - the maximum width the tree can be in cm - whether they want the tree to be evergreen, or **not** evergreen. A tree meets the requirements if: - the tree’s maximum height is **not** more than the user’s input **and** - the tree’s maximum width is **not** more than the user’s input **and** - the tree matches their evergreen input. The procedure creates a new array of all the `Tree` objects that meet all the requirements. The procedure calls `PrintTrees()` for each `Tree` object that meets all the requirements. If there are no trees that meet all the requirements, a suitable message is output. #### (i) Write program code for `ChooseTree()` . <span class="part-marks">6 marks</span> Save your program. Copy and paste the program code into part **2(e)(i)** in the evidence document. #### (ii) The procedure `ChooseTree()` needs amending. After the procedure has output the list of trees that meet all the requirements, the procedure needs to: <span class="part-marks">2 marks</span> - take as input the name of one of the trees that the user would like to buy from those that meet all the requirements - take as input the height of the tree in cm when it is bought - calculate and output how many years it will take the tree to grow to its maximum height. For example, the user inputs the tree, Beech. The tree’s height is 40 cm when bought. The tree will take 12 years to reach its maximum height of 400 cm. Write program code to amend `ChooseTree()` . Save your program. Copy and paste the program code into part **2(e)(ii)** in the evidence document. #### (iii) Write program code to amend the main program to call `ChooseTrees()` . <span class="part-marks">2 marks</span> Test your program with the following tree requirements: - a maximum height of 400 cm - a maximum width of 200 cm - a tree that is evergreen (does **not** lose its leaves). When asked for the tree selection, use the following data: - first tree name entered is ‘Blue Conifer’ - starting height is 100 cm. Take a screenshot of the outputs. Save your program. Copy and paste the screenshot into part **2(e)(iii)** in the evidence document.
Show mark scheme

2(a)(i)

VB.NET Class Tree Private TreeName As String Private HeightGrowth As Integer Private MaxHeight As Integer Private MaxWidth As Integer Private Evergreen As String Sub New(Name, HGrowth, MaxH, MaxW, PEvergreen) TreeName = Name HeightGrowth = HGrowth MaxHeight = MaxH MaxWidth = MaxW Evergreen = PEvergreen End Sub End Class Python class Tree: def init(self, Name, HGrowth, MaxH, MaxW, PEvergreen): self.__TreeName = Name self.__HeightGrowth = HGrowth self.__MaxHeight = MaxH self.__MaxWidth = MaxW self.__Evergreen = PEvergreen

2(a)(ii)

VB.NET Function GetTreeName() Return TreeName End Function Function GetMaxHeight() Return MaxHeight End Function Function GetMaxWIdth() Return MaxWidth End Function Function GetGrowth() Return HeightGrowth End Function Function GetEvergreen() Return Evergreen End Function Python def GetTreeName(self): return self.__TreeName def GetMaxHeight(self): return self.__MaxHeight def GetMaxWidth(self): return self.__MaxWidth def GetGrowth(self): return self.__HeightGrowth def GetEvergreen(self): return self.__Evergreen

2(b)

Python def ReadData(): TreeObjects=[] try: File = open("Trees.txt") TreeData = [] TreeData = File.read().split("\n") SplitTrees = [] for Item in TreeData: SplitTrees.append(Item.split(",")) File.close() for Item in SplitTrees: TreeObjects.append(Tree(Item[0],int(Item[1]),int(Item[2]),int(Item[3]),Item[4])) except IOError: print ("invalid file") return TreeObjects

2(c)

Python def PrintTrees(Item): Final = "does not lose its leaves" if Item.GetEvergreen() == "No": Final = "loses its leaves each year" print(Item.GetTreeName(), "has a maximum height", Item.GetMaxHeight(),"a maximum width",Item.GetMaxWidth(),"and grows", Item.GetGrowth(),"cm a year. It",Final)

2(d)(i) [2 marks]

1 mark each Calling ReadData() and storing/using return value (as array of type Tree )… …calling PrintTrees() with first object in returned array as parameter Tree[] TreeData = new Tree[20]; TreeData = ReadData(); PrintTrees(TreeData[0]); VB.NET Sub Main(args As String()) Dim TreeObjects(10) As Tree TreeObjects = ReadData() PrintTrees(Treeobjects(0)) End Sub Python TreeObjects = ReadData() PrintTrees(TreeObjects[0])

2(d)(ii) [1 mark]

Screenshot showing output

2(e)(i)

End If Dim count As Integer = 0 For x = 0 To 8 If Trees(x).GetMaxHeight() <= MaxHeight And Trees(x).GetMaxWidth() <= MaxWidth And keep = Trees(x).GetEvergreen() Then Options(count) = Trees(x) PrintTrees(Trees(x)) count = count + 1 End If Next x If count = 0 Then Console.WriteLine("No suitable trees") End If End Sub Python def ChooseTree(Trees): Evergreen = input("Do you want a tree that loses its leaves (enter lose), or keeps its leaves (enter keep)") MaxHeight = int(input("What is the maximum tree height in cm")) MaxWidth = int(input("What is the maximum tree width in cm")) Options = [] if Evergreen.lower() == "keep" or Evergreen.lower() == "keep leaves" or Evergreen.lower() == "keeps its leaves": keep = "Yes" else: keep = "No" for Item in Trees: if Item.GetMaxHeight() <= MaxHeight and Item.GetMaxWidth() <= MaxWidth and keep == Item.GetEvergreen(): Options.append(Item) PrintTrees(Item) if len(Options) == 0: print("No suitable trees")

2(e)(ii)

Integer Start; Float Height; Float Growth; Float Years; while(Valid == false){ System.out.println("Enter the name of the tree you want"); String Choice = scanner.nextLine(); for(Integer X = 0; X < Counter; X++){ if((Options[X].GetTreeName()).compareTo(Choice)==0){ Valid = true; Selected = Options[X]; System.out.println("Enter the height of the tree you would like to start with in cm"); Start = Integer.parseInt(scanner.nextLine()); Height = (Selected.GetMaxHeight()).floatValue(); Growth = (Selected.GetGrowth()).floatValue(); Years = (Height - Start) / Growth; System.out.println("Your tree should be full height in approximately "+ Years + " years"); } } Python: Valid = False while Valid == False: Choice = input("Enter the name of the tree you want") for Item in Options: if Item.GetTreeName() == Choice: Valid = True Selected = Item Start = int(input("Enter the height of the tree you would like to start with in cm")) Years = (Selected.GetMaxHeight() - Start)/Selected.GetGrowth() print("Your tree should be full height in approximately", Years,"years")

2(e)(iii) [2 marks]

1 mark each Screenshot shows the user requirements input (height 400, width 200, evergreen) and outputs the correct trees (Blue conifer and green conifer) Screenshot shows the tree selection input (Blue Conifer with height 100) and outputs the correct result (3 years / 3.75 / 4 years)

Q2
May/Jun 2024 Paper 4 v2

A binary tree stores data in ascending order. For example:

A computer program stores integers in a binary tree in ascending order. The program uses Object‑Oriented Programming (OOP).

The binary tree is stored as a 1D array of nodes. Each node contains a left pointer, a data value and a right pointer.

The class Node stores the data about a node.
Node Node
LeftPointer : INTEGER
Data : INTEGER
RightPointer : INTEGER
stores the index of the node to the left in the binary tree
stores the node’s data
stores the index of the node to the right in the binary tree
Constructor()
GetLeft()
GetRight()
GetData()
SetLeft()
SetRight()
SetData()
initialisesData to its parameter value
initialisesLeftPointer andRightPointer to −1
returns the left pointer
returns the right pointer
returns the data value
assigns the parameter to the left pointer
assigns the parameter to the right pointer
assigns the parameter to the data

(a) (i) Write program code to declare the class Node and its constructor. 4 marks

Do not declare the other methods.

Use the appropriate constructor for your programming language.

If you are writing in Python, include attribute declarations using comments.

Save your program as Question2_J24 .

Copy and paste the program code into part 2(a)(i) in the evidence document.

(ii) The get methods GetLeft(), GetRight() and GetData() each return the relevant attribute. 3 marks

Write program code for the three get methods.

Save your program.

Copy and paste the program code into part 2(a)(ii) in the evidence document.

(iii) The set methods SetLeft(), SetRight() and SetData() each take a parameter and then store this in the relevant attribute. 3 marks

Write program code for the three set methods.

Save your program.

Copy and paste the program code into part 2(a)(iii) in the evidence document.

The class TreeClass stores the data about the binary tree.
TreeClass TreeClass
Tree[0:19] : Node
FirstNode : INTEGER
NumberNodes : INTEGER
an array of 20 elements of typeNode
stores the index of the first node in the tree
stores the quantity of nodes in the tree
Constructor()
InsertNode()
OutputTree()
initialisesFirstNode to −1 andNumberNodes to 0
initialises each element inTree to aNode object with the
data value of −1
takes aNode object as a parameter, inserts it in the array
and updates the pointer for its parent node
outputs the left pointer, data and right pointer of each
node inTree

Nodes cannot be deleted from this tree.

(i) Write program code to declare the class TreeClass and its constructor. 4 marks

Do not declare the other methods.

Use the appropriate constructor for your programming language.

If you are writing in Python, include attribute declarations using comments.

Save your program.

Copy and paste the program code into part 2(b)(i) in the evidence document.

(ii) The method InsertNode() takes a Node object, NewNode, as a parameter and inserts it into the array Tree . 6 marks

InsertNode() first checks if the tree is empty.

If the tree is empty, InsertNode() :

  • stores NewNode in the array Tree at index NumberNodes

  • increments NumberNodes

  • stores 0 in FirstNode .

If the tree is not empty, InsertNode() :

  • stores NewNode in the array Tree at index NumberNodes

  • accesses the data in the array Tree at index FirstNode and compares it to the data in NewNode

  • repeatedly follows the pointers until the correct position for NewNode is found

  • once the position is found, InsertNode() sets the left or right pointer of its parent node

  • increments NumberNodes .

Write program code for InsertNode() .

Save your program.

Copy and paste the program code into part 2(b)(ii) in the evidence document.

(iii) The method OutputTree() outputs the left pointer, the data and the right pointer for each node that has been inserted into the tree. The outputs are in the order they are saved in the array. 4 marks

If there are no nodes in the array, the procedure outputs ‘No nodes’.

Write program code for OutputTree() .

Save your program.

Copy and paste the program code into part 2(b)(iii) in the evidence document. (c) (i) The main program declares an instance of TreeClass with the identifier TheTree . 1 mark

Write program code for the main program.

Save your program.

Copy and paste the program code into part 2(c)(i) in the evidence document.

(ii) The main program inserts the following integers into the binary tree in the order given: 4 marks

The main program then calls the method OutputTree() .

Write program code to amend the main program.

Save your program.

Copy and paste the program code into part 2(c)(ii) in the evidence document.

(iii) Test your program. 1 mark

Take a screenshot of the output(s).

Save your program.

Copy and paste the screenshot into part 2(c)(iii) in the evidence document.

A binary tree stores data in ascending order. For example: ![](../images/s24_42_q2_fig1.png) A computer program stores integers in a binary tree in ascending order. The program uses Object‑Oriented Programming (OOP). The binary tree is stored as a 1D array of nodes. Each node contains a left pointer, a data value and a right pointer. |The class Node stores the data about a node.|| |---|---| |**`Node`**|**`Node`**| |`LeftPointer : INTEGER`<br>`Data : INTEGER`<br>`RightPointer : INTEGER`|stores the index of the node to the left in the binary tree<br>stores the node’s data<br>stores the index of the node to the right in the binary tree| |`Constructor()`<br>`GetLeft()`<br>`GetRight()`<br>`GetData()`<br>`SetLeft()`<br>`SetRight()`<br>`SetData()`|initialises`Data` to its parameter value<br>initialises`LeftPointer` and`RightPointer` to −1<br>returns the left pointer<br>returns the right pointer<br>returns the data value<br>assigns the parameter to the left pointer<br>assigns the parameter to the right pointer<br>assigns the parameter to the data| **(a) (i)** Write program code to declare the class `Node` and its constructor. <span class="part-marks">4 marks</span> Do **not** declare the other methods. Use the appropriate constructor for your programming language. If you are writing in Python, include attribute declarations using comments. Save your program as **Question2_J24** . Copy and paste the program code into part **2(a)(i)** in the evidence document. #### (ii) The get methods `GetLeft()`, `GetRight()` and `GetData()` each return the relevant attribute. <span class="part-marks">3 marks</span> Write program code for the **three** get methods. Save your program. Copy and paste the program code into part **2(a)(ii)** in the evidence document. #### (iii) The set methods `SetLeft()`, `SetRight()` and `SetData()` each take a parameter and then store this in the relevant attribute. <span class="part-marks">3 marks</span> Write program code for the **three** set methods. Save your program. Copy and paste the program code into part **2(a)(iii)** in the evidence document. |The class TreeClass stores the data about the binary tree.|| |---|---| |**`TreeClass`**|**`TreeClass`**| |`Tree[0:19] : Node`<br>`FirstNode : INTEGER`<br>`NumberNodes : INTEGER`|an array of 20 elements of type`Node`<br>stores the index of the first node in the tree<br>stores the quantity of nodes in the tree| |`Constructor()`<br>`InsertNode()`<br>`OutputTree()`|initialises`FirstNode` to −1 and`NumberNodes` to 0<br>initialises each element in`Tree` to a`Node` object with the<br>data value of −1<br>takes a`Node` object as a parameter, inserts it in the array<br>and updates the pointer for its parent node<br>outputs the left pointer, data and right pointer of each<br>node in`Tree`| Nodes cannot be deleted from this tree. #### (i) Write program code to declare the class `TreeClass` and its constructor. <span class="part-marks">4 marks</span> Do **not** declare the other methods. Use the appropriate constructor for your programming language. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into part **2(b)(i)** in the evidence document. #### (ii) The method `InsertNode()` takes a `Node` object, `NewNode`, as a parameter and inserts it into the array `Tree` . <span class="part-marks">6 marks</span> `InsertNode()` first checks if the tree is empty. If the tree is empty, `InsertNode()` : - stores `NewNode` in the array `Tree` at index `NumberNodes` - increments `NumberNodes` - stores 0 in `FirstNode` . If the tree is **not** empty, `InsertNode()` : - stores `NewNode` in the array `Tree` at index `NumberNodes` - accesses the data in the array `Tree` at index `FirstNode` and compares it to the data in `NewNode` - repeatedly follows the pointers until the correct position for `NewNode` is found - once the position is found, `InsertNode()` sets the left or right pointer of its parent node - increments `NumberNodes` . Write program code for `InsertNode()` . Save your program. Copy and paste the program code into part **2(b)(ii)** in the evidence document. #### (iii) The method `OutputTree()` outputs the left pointer, the data and the right pointer for each node that has been inserted into the tree. The outputs are in the order they are saved in the array. <span class="part-marks">4 marks</span> If there are no nodes in the array, the procedure outputs ‘No nodes’. Write program code for `OutputTree()` . Save your program. Copy and paste the program code into part **2(b)(iii)** in the evidence document. **(c) (i)** The main program declares an instance of `TreeClass` with the identifier `TheTree` . <span class="part-marks">1 mark</span> Write program code for the main program. Save your program. Copy and paste the program code into part **2(c)(i)** in the evidence document. #### (ii) The main program inserts the following integers into the binary tree in the order given: <span class="part-marks">4 marks</span> The main program then calls the method `OutputTree()` . Write program code to amend the main program. Save your program. Copy and paste the program code into part **2(c)(ii)** in the evidence document. #### (iii) Test your program. <span class="part-marks">1 mark</span> Take a screenshot of the output(s). Save your program. Copy and paste the screenshot into part **2(c)(iii)** in the evidence document.
Show mark scheme

2(a)(i)

Python class Node(): def init (self, PData): self. LeftPointer = -1 #int self. Data = PData #int self. RightPointer = -1 #int

2(a)(ii)

def GetRight(self): return self. RightPointer def GetData(self): return self. Data

2(a)(iii)

self. RightPointer = NewRight def SetData(self, NewData): self. Data = NewData

2(b)(i)

For x = 0 To 19 Tree(x) = New Node(-1) Next End Sub End Class Python class TreeClass(): def init (self): self. Tree = [] #type node 20 spaces self. FirstNode = -1 #int self. NumberNodes = 0 #int for x in range(20): self. Tree.append(Node(-1))

2(b)(ii)

NodeAccess = self. Tree[NodeAccess].GetLeft() Direction = "left" elif NewNode.GetData() > self. Tree[NodeAccess].GetData(): NodeAccess = self. Tree[NodeAccess].GetRight() Direction = "right" if(Direction == "left"): self. Tree[Previous].SetLeft(self. NumberNodes) else: self. Tree[Previous].SetRight(self. NumberNodes) self. NumberNodes = self. NumberNodes + 1

2(b)(iii)

Python def OutputTree(self): if self. NumberNodes == 0: print("No nodes") else: for x in range(0, self. NumberNodes): print(self. Tree[x].GetLeft(), " ", self. Tree[x].GetData(), " ",self. Tree[x].GetRight())

2(c)(i) [1 mark]

1 mark for Instance of TreeClass created with identifier TheTree public static void main(String args[]){ TreeClass TheTree = new TreeClass(); VB.NET Sub Main(args As String()) Dim TheTree As TreeClass = New TreeClass() End Sub Python TheTree = TreeClass()

2(c)(ii)

Python TheTree = TreeClass() TheTree.InsertNode(Node(10)) TheTree.InsertNode(Node(11)) TheTree.InsertNode(Node(5)) TheTree.InsertNode(Node(1)) TheTree.InsertNode(Node(20)) TheTree.InsertNode(Node(7)) TheTree.InsertNode(Node(15)) TheTree.OutputTree()

2(c)(iii) [1 mark]

1 mark for correct output e.g.

Q2
May/Jun 2024 Paper 4 v3

A computer program will store data about trees.

The user can enter their requirements for a tree and a suitable tree will be selected.

The program is written using object‑oriented programming.

The class Tree stores data about the trees. Tree
Tree Tree
TreeName : STRING
HeightGrowth : INTEGER
MaxHeight : INTEGER
MaxWidth : INTEGER
Evergreen : STRING
stores the name of the tree
stores the number of cm the tree will grow each year
stores the maximum height in cm that the tree will grow
stores the maximum width in cm that the tree will grow
stores whether the tree keeps its leaves as"Yes", or
loses its leaves as"No"
Constructor()
GetTreeName()
GetGrowth()
GetMaxHeight()
GetMaxWidth()
GetEvergreen()
initialisesTreeName, HeightGrowth, MaxHeight,
MaxWidth andEvergreen to its parameter values
returns the name of the tree
returns the number of cm the tree will grow each year
returns the maximum height in cm that the tree will grow
returns the maximum width in cm that the tree will grow
returns whether the tree keeps its leaves or loses its
leaves

(a) (i) Write program code to declare the class Tree and its constructor. 4 marks

Do not declare the other methods.

Use the appropriate constructor for your programming language.

All attributes must be private.

If you are writing in Python, include attribute declarations using comments.

Save your program as Question2_J24 .

Copy and paste the program code into part 2(a)(i) in the evidence document.

(ii) The get methods GetTreeName(), GetGrowth(), GetMaxHeight(), GetMaxWidth() and GetEvergreen() each return the relevant attribute. 3 marks

Write program code for the get methods.

Save your program.

Copy and paste the program code into part 2(a)(ii) in the evidence document.

(b) The text file Trees.txt stores data about 9 trees. 7 marks

The data in the file is stored in the format:

Tree name,Height growth each year,Maximum height,Maximum width,Evergreen

For example, the first row of data is:

Beech,30,400,200,No

The tree is a Beech. It can grow 30 cm each year. It has a maximum height of 400 cm. It has a maximum width of 200 cm. It is not evergreen (it loses its leaves).

The function ReadData() :

  • creates an array of type Tree

  • reads the data from the file

  • raises an exception if the file is not found

  • creates a new object of type Tree for each tree in the file

  • appends each object to the array

  • returns the array.

Write program code for ReadData() .

Save your program.

Copy and paste the program code into part 2(b) in the evidence document.

(c) The procedure PrintTrees() takes a Tree object as a parameter and outputs the tree’s name, height growth each year, maximum height, maximum width and whether it is evergreen. 4 marks

The output message changes depending on whether it is evergreen.

If it is evergreen, it is in the format:

TreeName has a maximum height MaxHeight a maximum width MaxWidth and grows HeightGrowth cm a year. It does not lose its leaves.

If it is not evergreen, it is in the format:

TreeName has a maximum height MaxHeight a maximum width MaxWidth and grows HeightGrowth cm a year. It loses its leaves each year.

Write program code for PrintTrees() .

Save your program.

Copy and paste the program code into part 2(c) in the evidence document.

(d) The main program calls ReadData(), stores the return value and calls PrintTrees() with the first object in the returned array.

(i) Write program code for the main program. 2 marks

Save your program.

Copy and paste the program code into part 2(d)(i) in the evidence document.

(ii) Test your program. 1 mark

Take a screenshot of the output(s).

Save your program.

Copy and paste the screenshot into part 2(d)(ii) in the evidence document.

(e) The procedure ChooseTree() takes an array of Tree objects as a parameter.

The procedure prompts the user to input their requirements for a tree. The user needs to enter:

  • the maximum height the tree can be in cm

  • the maximum width the tree can be in cm

  • whether they want the tree to be evergreen, or not evergreen.

A tree meets the requirements if:

  • the tree’s maximum height is not more than the user’s input

and

  • the tree’s maximum width is not more than the user’s input

and

  • the tree matches their evergreen input.

The procedure creates a new array of all the Tree objects that meet all the requirements.

The procedure calls PrintTrees() for each Tree object that meets all the requirements. If there are no trees that meet all the requirements, a suitable message is output.

(i) Write program code for ChooseTree() . 6 marks

Save your program.

Copy and paste the program code into part 2(e)(i) in the evidence document.

(ii) The procedure ChooseTree() needs amending. After the procedure has output the list of trees that meet all the requirements, the procedure needs to: 2 marks

  • take as input the name of one of the trees that the user would like to buy from those that meet all the requirements

  • take as input the height of the tree in cm when it is bought

  • calculate and output how many years it will take the tree to grow to its maximum height.

For example, the user inputs the tree, Beech. The tree’s height is 40 cm when bought. The tree will take 12 years to reach its maximum height of 400 cm.

Write program code to amend ChooseTree() .

Save your program.

Copy and paste the program code into part 2(e)(ii) in the evidence document.

(iii) Write program code to amend the main program to call ChooseTrees() . 2 marks

Test your program with the following tree requirements:

  • a maximum height of 400 cm

  • a maximum width of 200 cm

  • a tree that is evergreen (does not lose its leaves).

When asked for the tree selection, use the following data:

  • first tree name entered is ‘Blue Conifer’

  • starting height is 100 cm.

Take a screenshot of the outputs.

Save your program.

Copy and paste the screenshot into part 2(e)(iii) in the evidence document.

A computer program will store data about trees. The user can enter their requirements for a tree and a suitable tree will be selected. The program is written using object‑oriented programming. |The class Tree stores data about the trees. Tree|| |---|---| |**`Tree`**|**`Tree`**| |`TreeName : STRING`<br>`HeightGrowth : INTEGER`<br>`MaxHeight : INTEGER`<br>`MaxWidth : INTEGER`<br>`Evergreen : STRING`|stores the name of the tree<br>stores the number of cm the tree will grow each year<br>stores the maximum height in cm that the tree will grow<br>stores the maximum width in cm that the tree will grow<br>stores whether the tree keeps its leaves as`"Yes"`, or<br>loses its leaves as`"No"`| |`Constructor()`<br>`GetTreeName()`<br>`GetGrowth()`<br>`GetMaxHeight()`<br>`GetMaxWidth()`<br>`GetEvergreen()`|initialises`TreeName`, `HeightGrowth`, `MaxHeight`, <br>`MaxWidth` and`Evergreen` to its parameter values<br>returns the name of the tree<br>returns the number of cm the tree will grow each year<br>returns the maximum height in cm that the tree will grow<br>returns the maximum width in cm that the tree will grow<br>returns whether the tree keeps its leaves or loses its<br>leaves| **(a) (i)** Write program code to declare the class `Tree` and its constructor. <span class="part-marks">4 marks</span> Do **not** declare the other methods. Use the appropriate constructor for your programming language. All attributes must be private. If you are writing in Python, include attribute declarations using comments. Save your program as **Question2_J24** . Copy and paste the program code into part **2(a)(i)** in the evidence document. #### (ii) The get methods `GetTreeName()`, `GetGrowth()`, `GetMaxHeight()`, `GetMaxWidth()` and `GetEvergreen()` each return the relevant attribute. <span class="part-marks">3 marks</span> Write program code for the get methods. Save your program. Copy and paste the program code into part **2(a)(ii)** in the evidence document. ### (b) The text file `Trees.txt` stores data about 9 trees. <span class="part-marks">7 marks</span> The data in the file is stored in the format: Tree name,Height growth each year,Maximum height,Maximum width,Evergreen For example, the first row of data is: Beech,30,400,200,No The tree is a Beech. It can grow 30 cm each year. It has a maximum height of 400 cm. It has a maximum width of 200 cm. It is **not** evergreen (it loses its leaves). The function `ReadData()` : - creates an array of type `Tree` - reads the data from the file - raises an exception if the file is **not** found - creates a new object of type `Tree` for each tree in the file - appends each object to the array - returns the array. Write program code for `ReadData()` . Save your program. Copy and paste the program code into part **2(b)** in the evidence document. ### (c) The procedure `PrintTrees()` takes a `Tree` object as a parameter and outputs the tree’s name, height growth each year, maximum height, maximum width and whether it is evergreen. <span class="part-marks">4 marks</span> The output message changes depending on whether it is evergreen. If it is evergreen, it is in the format: `TreeName` has a maximum height `MaxHeight` a maximum width `MaxWidth` and grows `HeightGrowth` cm a year. It does not lose its leaves. If it is **not** evergreen, it is in the format: `TreeName` has a maximum height `MaxHeight` a maximum width `MaxWidth` and grows `HeightGrowth` cm a year. It loses its leaves each year. Write program code for `PrintTrees()` . Save your program. Copy and paste the program code into part **2(c)** in the evidence document. ### (d) The main program calls `ReadData()`, stores the return value and calls `PrintTrees()` with the first object in the returned array. #### (i) Write program code for the main program. <span class="part-marks">2 marks</span> Save your program. Copy and paste the program code into part **2(d)(i)** in the evidence document. #### (ii) Test your program. <span class="part-marks">1 mark</span> Take a screenshot of the output(s). Save your program. Copy and paste the screenshot into part **2(d)(ii)** in the evidence document. ### (e) The procedure `ChooseTree()` takes an array of `Tree` objects as a parameter. The procedure prompts the user to input their requirements for a tree. The user needs to enter: - the maximum height the tree can be in cm - the maximum width the tree can be in cm - whether they want the tree to be evergreen, or **not** evergreen. A tree meets the requirements if: - the tree’s maximum height is **not** more than the user’s input **and** - the tree’s maximum width is **not** more than the user’s input **and** - the tree matches their evergreen input. The procedure creates a new array of all the `Tree` objects that meet all the requirements. The procedure calls `PrintTrees()` for each `Tree` object that meets all the requirements. If there are no trees that meet all the requirements, a suitable message is output. #### (i) Write program code for `ChooseTree()` . <span class="part-marks">6 marks</span> Save your program. Copy and paste the program code into part **2(e)(i)** in the evidence document. #### (ii) The procedure `ChooseTree()` needs amending. After the procedure has output the list of trees that meet all the requirements, the procedure needs to: <span class="part-marks">2 marks</span> - take as input the name of one of the trees that the user would like to buy from those that meet all the requirements - take as input the height of the tree in cm when it is bought - calculate and output how many years it will take the tree to grow to its maximum height. For example, the user inputs the tree, Beech. The tree’s height is 40 cm when bought. The tree will take 12 years to reach its maximum height of 400 cm. Write program code to amend `ChooseTree()` . Save your program. Copy and paste the program code into part **2(e)(ii)** in the evidence document. #### (iii) Write program code to amend the main program to call `ChooseTrees()` . <span class="part-marks">2 marks</span> Test your program with the following tree requirements: - a maximum height of 400 cm - a maximum width of 200 cm - a tree that is evergreen (does **not** lose its leaves). When asked for the tree selection, use the following data: - first tree name entered is ‘Blue Conifer’ - starting height is 100 cm. Take a screenshot of the outputs. Save your program. Copy and paste the screenshot into part **2(e)(iii)** in the evidence document.
Show mark scheme

2(a)(i)

VB.NET Class Tree Private TreeName As String Private HeightGrowth As Integer Private MaxHeight As Integer Private MaxWidth As Integer Private Evergreen As String Sub New(Name, HGrowth, MaxH, MaxW, PEvergreen) TreeName = Name HeightGrowth = HGrowth MaxHeight = MaxH MaxWidth = MaxW Evergreen = PEvergreen End Sub End Class Python class Tree: def init(self, Name, HGrowth, MaxH, MaxW, PEvergreen): self.__TreeName = Name self.__HeightGrowth = HGrowth self.__MaxHeight = MaxH self.__MaxWidth = MaxW self.__Evergreen = PEvergreen

2(a)(ii)

VB.NET Function GetTreeName() Return TreeName End Function Function GetMaxHeight() Return MaxHeight End Function Function GetMaxWIdth() Return MaxWidth End Function Function GetGrowth() Return HeightGrowth End Function Function GetEvergreen() Return Evergreen End Function Python def GetTreeName(self): return self.__TreeName def GetMaxHeight(self): return self.__MaxHeight def GetMaxWidth(self): return self.__MaxWidth def GetGrowth(self): return self.__HeightGrowth def GetEvergreen(self): return self.__Evergreen

2(b)

Python def ReadData(): TreeObjects=[] try: File = open("Trees.txt") TreeData = [] TreeData = File.read().split("\n") SplitTrees = [] for Item in TreeData: SplitTrees.append(Item.split(",")) File.close() for Item in SplitTrees: TreeObjects.append(Tree(Item[0],int(Item[1]),int(Item[2]),int(Item[3]),Item[4])) except IOError: print ("invalid file") return TreeObjects

2(c)

Python def PrintTrees(Item): Final = "does not lose its leaves" if Item.GetEvergreen() == "No": Final = "loses its leaves each year" print(Item.GetTreeName(), "has a maximum height", Item.GetMaxHeight(),"a maximum width",Item.GetMaxWidth(),"and grows", Item.GetGrowth(),"cm a year. It",Final)

2(d)(i) [2 marks]

1 mark each Calling ReadData() and storing/using return value (as array of type Tree )… …calling PrintTrees() with first object in returned array as parameter Tree[] TreeData = new Tree[20]; TreeData = ReadData(); PrintTrees(TreeData[0]); VB.NET Sub Main(args As String()) Dim TreeObjects(10) As Tree TreeObjects = ReadData() PrintTrees(Treeobjects(0)) End Sub Python TreeObjects = ReadData() PrintTrees(TreeObjects[0])

2(d)(ii) [1 mark]

Screenshot showing output

2(e)(i)

End If Dim count As Integer = 0 For x = 0 To 8 If Trees(x).GetMaxHeight() <= MaxHeight And Trees(x).GetMaxWidth() <= MaxWidth And keep = Trees(x).GetEvergreen() Then Options(count) = Trees(x) PrintTrees(Trees(x)) count = count + 1 End If Next x If count = 0 Then Console.WriteLine("No suitable trees") End If End Sub Python def ChooseTree(Trees): Evergreen = input("Do you want a tree that loses its leaves (enter lose), or keeps its leaves (enter keep)") MaxHeight = int(input("What is the maximum tree height in cm")) MaxWidth = int(input("What is the maximum tree width in cm")) Options = [] if Evergreen.lower() == "keep" or Evergreen.lower() == "keep leaves" or Evergreen.lower() == "keeps its leaves": keep = "Yes" else: keep = "No" for Item in Trees: if Item.GetMaxHeight() <= MaxHeight and Item.GetMaxWidth() <= MaxWidth and keep == Item.GetEvergreen(): Options.append(Item) PrintTrees(Item) if len(Options) == 0: print("No suitable trees")

2(e)(ii)

Integer Start; Float Height; Float Growth; Float Years; while(Valid == false){ System.out.println("Enter the name of the tree you want"); String Choice = scanner.nextLine(); for(Integer X = 0; X < Counter; X++){ if((Options[X].GetTreeName()).compareTo(Choice)==0){ Valid = true; Selected = Options[X]; System.out.println("Enter the height of the tree you would like to start with in cm"); Start = Integer.parseInt(scanner.nextLine()); Height = (Selected.GetMaxHeight()).floatValue(); Growth = (Selected.GetGrowth()).floatValue(); Years = (Height - Start) / Growth; System.out.println("Your tree should be full height in approximately "+ Years + " years"); } } Python: Valid = False while Valid == False: Choice = input("Enter the name of the tree you want") for Item in Options: if Item.GetTreeName() == Choice: Valid = True Selected = Item Start = int(input("Enter the height of the tree you would like to start with in cm")) Years = (Selected.GetMaxHeight() - Start)/Selected.GetGrowth() print("Your tree should be full height in approximately", Years,"years")

2(e)(iii) [2 marks]

1 mark each Screenshot shows the user requirements input (height 400, width 200, evergreen) and outputs the correct trees (Blue conifer and green conifer) Screenshot shows the tree selection input (Blue Conifer with height 100) and outputs the correct result (3 years / 3.75 / 4 years)

Q11
Oct/Nov 2023 Paper 3 v1

A declarative programming language is used to represent subjects that students can choose to study.

Students must choose two subjects.

  01 subject(mathematics).
  02 subject(physics).
  03 subject(chemistry).
  04 subject(computer_science).
  05 subject(geography).
  06 subject(history).
  07 subject(english).
  08 subject(biology).
  09 student(tomaz).
  10 student(josephine).
  11 student(elspeth).
  12 student(nico).
  13 student(teresa).
  14 student(pietre).
  15 choice1(tomaz, mathematics).
  16 choice1(teresa, chemistry).
  17 choice1(pietre, mathematics).
  18 choice1(nico, mathematics).
  19 choice1(elspeth, chemistry).
  20 choice2(tomaz, computer_science).
  21 choice2(nico, geography).

|uses have the|meanings:|
|---|---|
|**Clause**|**Meaning**|
|`01`|Mathematics is a subject.|
|`09`|Tomaz is a student.|
|`15`|Tomaz has chosen mathematics as his first choice.|
|`20`|Tomaz has chosen computer science as his second choice.|

(a) Anthony is a student who would like to study history and geography. 3 marks

Write additional clauses to represent this information.

22

23

24

(b) Using the variable X, the goal:

      choice1(X, chemistry)

returns

      X = teresa, elspeth

Write the result returned by the goal:

      choice1(X, mathematics)

X = [1]

(c) Students must choose two different subjects such that: 4 marks

N may choose S, if N is a student and S is a subject and N has not chosen S as the first choice.

Write this as a rule.

    may_choose_subject(N, S)

IF

A **declarative** programming language is used to represent subjects that students can choose to study. Students must choose two subjects. ``` 01 subject(mathematics). 02 subject(physics). 03 subject(chemistry). 04 subject(computer_science). 05 subject(geography). 06 subject(history). 07 subject(english). 08 subject(biology). 09 student(tomaz). 10 student(josephine). 11 student(elspeth). 12 student(nico). 13 student(teresa). 14 student(pietre). 15 choice1(tomaz, mathematics). 16 choice1(teresa, chemistry). 17 choice1(pietre, mathematics). 18 choice1(nico, mathematics). 19 choice1(elspeth, chemistry). 20 choice2(tomaz, computer_science). 21 choice2(nico, geography). |uses have the|meanings:| |---|---| |**Clause**|**Meaning**| |`01`|Mathematics is a subject.| |`09`|Tomaz is a student.| |`15`|Tomaz has chosen mathematics as his first choice.| |`20`|Tomaz has chosen computer science as his second choice.| ``` ### (a) Anthony is a student who would like to study history and geography. <span class="part-marks">3 marks</span> Write additional clauses to represent this information. `22` `23` `24` ### (b) Using the variable `X`, the goal: ``` choice1(X, chemistry) ``` returns ``` X = teresa, elspeth ``` Write the result returned by the goal: ``` choice1(X, mathematics) ``` `X =` [1] ### (c) Students must choose two different subjects such that: <span class="part-marks">4 marks</span> N may choose S, if N is a student and S is a subject and N has not chosen S as the first choice. Write this as a rule. ``` may_choose_subject(N, S) ``` `IF`
Show mark scheme

11(a) [3 marks]

One mark for each correctly completed clause ( Max 3 ) (22) student(anthony). (23) choice1(anthony, history). (24) choice2(anthony, geography). X = tomaz, pietre, nico

11(c) [4 marks]

One mark per mark point ( Max 4 ) • student (N) • subject(S) • choice1(N, S) • all logical operators correct with no additional code (see example answers) Example answers: may_choose_subject(N, S) IF student(N) AND subject(S) AND NOT choice1(N, S) may_choose_subject(N, S) IF NOT choice1(N, S), student(N), subject(S)

Q10
Oct/Nov 2023 Paper 3 v2
Show mark scheme

10 [4 marks]

One mark per mark point – SIMD ( Max 2 ) MP1 Single Instruction, Multiple Data (architecture) // Performs the same operation on multiple different data streams simultaneously. MP2 The instructions can be performed sequentially, taking advantage of pipelining . MP3 Parallel computers with multiple processors. One mark per mark point – MISD ( Max 2 ) MP4 Multiple Instruction, Single Data (architecture) // Performs different operations on the same data stream. MP5 Each processor works on the same data stream independently. MP6 Parallel computers with multiple processors.

Q11
Oct/Nov 2023 Paper 3 v2

(b) Using the variable P, the goal:

      enjoys(P, camping)

returns

      P = elijah, joseph

Write the result returned by the goal:

      enjoys(P, climbing)

P = [1]

(c) N is a person who might enjoy H if H is a hobby and N does not dislike H. 4 marks 2 marks

Write this as a rule.

    might_enjoy(N, H)

IF 12 (a) Describe, with an example, what is meant by an exception .

### (b) Using the variable `P`, the goal: ``` enjoys(P, camping) ``` returns ``` P = elijah, joseph ``` Write the result returned by the goal: ``` enjoys(P, climbing) ``` `P =` [1] ### (c) N is a person who might enjoy H if H is a hobby and N does not dislike H. <span class="part-marks">4 marks</span> <span class="part-marks">2 marks</span> Write this as a rule. ``` might_enjoy(N, H) ``` `IF` **12 (a)** Describe, with an example, what is meant by an **exception** .
Show mark scheme

11(a) [4 marks]

One mark for each correctly completed clause ( Max 4 ) 20 person(carlos). 21 hobby(cycling). 22 enjoys(carlos, cycling). 23 dislikes(carlos, music). P = toby, nina

11(c) [4 marks]

One mark per mark point ( Max 4 ) • person(N) • hobby(H) • dislikes(N, H) • all logical operators correct with no additional code (see example answers) Example answers: might_enjoy(N, H) IF person(N) AND hobby(H) AND NOT dislikes(N, H ) might_enjoy(N, H) IF NOT dislikes(N, H), person(N), hobby(H)

Q11
Oct/Nov 2023 Paper 3 v3

A declarative programming language is used to represent subjects that students can choose to study.

Students must choose two subjects.

  01 subject(mathematics).
  02 subject(physics).
  03 subject(chemistry).
  04 subject(computer_science).
  05 subject(geography).
  06 subject(history).
  07 subject(english).
  08 subject(biology).
  09 student(tomaz).
  10 student(josephine).
  11 student(elspeth).
  12 student(nico).
  13 student(teresa).
  14 student(pietre).
  15 choice1(tomaz, mathematics).
  16 choice1(teresa, chemistry).
  17 choice1(pietre, mathematics).
  18 choice1(nico, mathematics).
  19 choice1(elspeth, chemistry).
  20 choice2(tomaz, computer_science).
  21 choice2(nico, geography).

|uses have the|meanings:|
|---|---|
|**Clause**|**Meaning**|
|`01`|Mathematics is a subject.|
|`09`|Tomaz is a student.|
|`15`|Tomaz has chosen mathematics as his first choice.|
|`20`|Tomaz has chosen computer science as his second choice.|

(a) Anthony is a student who would like to study history and geography. 3 marks

Write additional clauses to represent this information.

22

23

24

(b) Using the variable X, the goal:

      choice1(X, chemistry)

returns

      X = teresa, elspeth

Write the result returned by the goal:

      choice1(X, mathematics)

X = [1]

(c) Students must choose two different subjects such that: 4 marks

N may choose S, if N is a student and S is a subject and N has not chosen S as the first choice.

Write this as a rule.

    may_choose_subject(N, S)

IF

A **declarative** programming language is used to represent subjects that students can choose to study. Students must choose two subjects. ``` 01 subject(mathematics). 02 subject(physics). 03 subject(chemistry). 04 subject(computer_science). 05 subject(geography). 06 subject(history). 07 subject(english). 08 subject(biology). 09 student(tomaz). 10 student(josephine). 11 student(elspeth). 12 student(nico). 13 student(teresa). 14 student(pietre). 15 choice1(tomaz, mathematics). 16 choice1(teresa, chemistry). 17 choice1(pietre, mathematics). 18 choice1(nico, mathematics). 19 choice1(elspeth, chemistry). 20 choice2(tomaz, computer_science). 21 choice2(nico, geography). |uses have the|meanings:| |---|---| |**Clause**|**Meaning**| |`01`|Mathematics is a subject.| |`09`|Tomaz is a student.| |`15`|Tomaz has chosen mathematics as his first choice.| |`20`|Tomaz has chosen computer science as his second choice.| ``` ### (a) Anthony is a student who would like to study history and geography. <span class="part-marks">3 marks</span> Write additional clauses to represent this information. `22` `23` `24` ### (b) Using the variable `X`, the goal: ``` choice1(X, chemistry) ``` returns ``` X = teresa, elspeth ``` Write the result returned by the goal: ``` choice1(X, mathematics) ``` `X =` [1] ### (c) Students must choose two different subjects such that: <span class="part-marks">4 marks</span> N may choose S, if N is a student and S is a subject and N has not chosen S as the first choice. Write this as a rule. ``` may_choose_subject(N, S) ``` `IF`
Show mark scheme

11(a) [3 marks]

One mark for each correctly completed clause ( Max 3 ) (22) student(anthony). (23) choice1(anthony, history). (24) choice2(anthony, geography). X = tomaz, pietre, nico

11(c) [4 marks]

One mark per mark point ( Max 4 ) • student (N) • subject(S) • choice1(N, S) • all logical operators correct with no additional code (see example answers) Example answers: may_choose_subject(N, S) IF student(N) AND subject(S) AND NOT choice1(N, S) may_choose_subject(N, S) IF NOT choice1(N, S), student(N), subject(S)

Q3
Oct/Nov 2023 Paper 4 v1

A computer game is written using object-oriented programming.

The game has multiple characters that can move around the screen.

The class Character stores data about the characters. Each character has a name, a curren (horizontal) position and a current Y (vertical) position.
Character Character
Name : STRING
XPosition : INTEGER
YPosition : INTEGER
stores the name of the character as a string
stores the X position as an integer
stores the Y position as an integer
Constructor()
GetXPosition()
GetYPosition()
SetXPosition()
SetYPosition()
Move()
initialisesName, XPosition andYPosition to its
parameter values
returns the X position
returns the Y position
adds the parameter to the X position
validates that the new X position is between 0 and 10 000
inclusive
adds the parameter to the Y position
validates that the new Y position is between 0 and 10 000
inclusive
takes a direction as a parameter and calls either
SetXPosition orSetYPosition with an integer value

(a) (i) Write program code to declare the class Character and its constructor. 4 marks

Do not declare the other methods.

Use your programming language’s appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program as Question3_N23 .

Copy and paste the program code into part 3(a)(i) in the evidence document.

(ii) The get methods GetXPosition() and GetYPosition() each return the relevant attribute. 3 marks

Write program code for the get methods.

Save your program.

Copy and paste the program code into part 3(a)(ii) in the evidence document.

(iii) The set methods SetXPosition() and SetYPosition() each take a value as a parameter and add this to the current X or Y position. 4 marks

If the new value exceeds 10 000, it is limited to 10 000.

If the new value is below 0, it is limited to 0.

Write program code for the set methods.

Save your program.

Copy and paste the program code into part 3(a)(iii) in the evidence document.

(iv) The method Move() takes a string parameter: "up", "down", "left" or "right" . 4 marks

The table shows the change each direction will make to the X or Y position.

Use the appropriate method to change the position value.

Direction Value change
up Y position + 10
down Y position − 10
left X position − 10
right X position + 10

Write program code for Move() .

Save your program.

Copy and paste the program code into part 3(a)(iv) in the evidence document.

(b) Write program code to declare a new instance of Character with the identifier Jack . 2 marks

The starting X position is 50 and the starting Y position is 50, the character’s name is Jack.

Save your program.

Copy and paste the program code into part 3(b) in the evidence document.

(c) The class BikeCharacter inherits from the class Character.
BikeCharacter BikeCharacter
Constructor()
Move()
takesName, XPosition andYPosition as parameters
calls its parent class constructor with the appropriate values
overrides the methodMove() from the parent class by
changing either the X position or the Y position by 20
instead of 10

(i) Write program code to declare the class BikeCharacter and its constructor. 3 marks

Do not declare the other method.

Use your programming language’s appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program.

Copy and paste the program code into part 3(c)(i) in the evidence document.

(ii) The method Move() overrides the method from the parent class. 2 marks

The table shows the change each direction will make to the X or Y position.

Direction Value change
up Y position + 20
down Y position − 20
left X position − 20
right X position + 20

Write program code for Move() .

Save your program.

Copy and paste the program code into part 3(c)(ii) in the evidence document.

(d) Write program code to declare a new instance of BikeCharacter with the identifier Karla . 1 mark

The starting X position is 100, the starting Y position is 50 and the character’s name is Karla.

Save your program.

Copy and paste the program code into part 3(d) in the evidence document. (e) (i) Write program code to: 5 marks

  • take as input which of the two characters the user would like to move

  • take as input the direction the user would like the character to move

  • call the appropriate method to move the character

  • output the character’s new X and Y position in an appropriate format, for example:

          "Karla's new position is X = 100 Y = 200"

All inputs require appropriate prompts and must be validated.

Save your program.

Copy and paste the program code into part 3(e)(i) in the evidence document.

(ii) Test your program twice with the following inputs. 2 marks

Test 1: jack right

Test 2: karla down

Take a screenshot of the output.

Save your program.

Copy and paste the screenshot into part 3(e)(ii) in the evidence document.

A computer game is written using object-oriented programming. The game has multiple characters that can move around the screen. |The class Character stores data about the characters. Each character has a name, a curren (horizontal) position and a current Y (vertical) position.|| |---|---| |**`Character`**|**`Character`**| |`Name : STRING`<br>`XPosition : INTEGER`<br>`YPosition : INTEGER`|stores the name of the character as a string<br>stores the X position as an integer<br>stores the Y position as an integer| |`Constructor()`<br>`GetXPosition()`<br>`GetYPosition()`<br>`SetXPosition()`<br>`SetYPosition()`<br>`Move()`|initialises`Name`, `XPosition` and`YPosition` to its<br>parameter values<br>returns the X position<br>returns the Y position<br>adds the parameter to the X position<br>validates that the new X position is between 0 and 10 000<br>inclusive<br>adds the parameter to the Y position<br>validates that the new Y position is between 0 and 10 000<br>inclusive<br>takes a direction as a parameter and calls either<br>`SetXPosition` or`SetYPosition` with an integer value| **(a) (i)** Write program code to declare the class `Character` and its constructor. <span class="part-marks">4 marks</span> Do **not** declare the other methods. Use your programming language’s appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program as **Question3_N23** . Copy and paste the program code into part **3(a)(i)** in the evidence document. #### (ii) The get methods `GetXPosition()` and `GetYPosition()` each return the relevant attribute. <span class="part-marks">3 marks</span> Write program code for the get methods. Save your program. Copy and paste the program code into part **3(a)(ii)** in the evidence document. #### (iii) The set methods `SetXPosition()` and `SetYPosition()` each take a value as a parameter and add this to the current X or Y position. <span class="part-marks">4 marks</span> If the new value exceeds 10 000, it is limited to 10 000. If the new value is below 0, it is limited to 0. Write program code for the set methods. Save your program. Copy and paste the program code into part **3(a)(iii)** in the evidence document. #### (iv) The method `Move()` takes a string parameter: `"up"`, `"down"`, `"left"` or `"right"` . <span class="part-marks">4 marks</span> The table shows the change each direction will make to the X or Y position. Use the appropriate method to change the position value. |Direction|Value change| |---|---| |up|Y position + 10| |down|Y position − 10| |left|X position − 10| |right|X position + 10| Write program code for `Move()` . Save your program. Copy and paste the program code into part **3(a)(iv)** in the evidence document. ### (b) Write program code to declare a new instance of `Character` with the identifier `Jack` . <span class="part-marks">2 marks</span> The starting X position is 50 and the starting Y position is 50, the character’s name is Jack. Save your program. Copy and paste the program code into part **3(b)** in the evidence document. |(c) The class BikeCharacter inherits from the class Character.|| |---|---| |**`BikeCharacter`**|**`BikeCharacter`**| |`Constructor()`<br>`Move()`|takes`Name`, `XPosition` and`YPosition` as parameters<br>calls its parent class constructor with the appropriate values<br>overrides the method`Move()` from the parent class by<br>changing either the X position or the Y position by 20<br>instead of 10| #### (i) Write program code to declare the class `BikeCharacter` and its constructor. <span class="part-marks">3 marks</span> Do **not** declare the other method. Use your programming language’s appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into part **3(c)(i)** in the evidence document. #### (ii) The method `Move()` overrides the method from the parent class. <span class="part-marks">2 marks</span> The table shows the change each direction will make to the X or Y position. |Direction|Value change| |---|---| |up|Y position + 20| |down|Y position − 20| |left|X position − 20| |right|X position + 20| Write program code for `Move()` . Save your program. Copy and paste the program code into part **3(c)(ii)** in the evidence document. ### (d) Write program code to declare a new instance of `BikeCharacter` with the identifier `Karla` . <span class="part-marks">1 mark</span> The starting X position is 100, the starting Y position is 50 and the character’s name is Karla. Save your program. Copy and paste the program code into part **3(d)** in the evidence document. **(e) (i)** Write program code to: <span class="part-marks">5 marks</span> - take as input which of the two characters the user would like to move - take as input the direction the user would like the character to move - call the appropriate method to move the character - output the character’s new X and Y position in an appropriate format, for example: ``` "Karla's new position is X = 100 Y = 200" ``` All inputs require appropriate prompts and must be validated. Save your program. Copy and paste the program code into part **3(e)(i)** in the evidence document. #### (ii) Test your program twice with the following inputs. <span class="part-marks">2 marks</span> Test 1: jack right Test 2: karla down Take a screenshot of the output. Save your program. Copy and paste the screenshot into part **3(e)(ii)** in the evidence document.
Show mark scheme

3(a)(i)

Python class Character: #self.XPosition integer #self.YPosition integer #self.Name string def init (self, XPositionP, YPositionP, NameP): self.XPosition = XPositionP self.YPosition = YPositionP self.Name = NameP

3(a)(ii) [3 marks]

One mark each • 1 get header with no parameter … • … returning correct value • 2nd get method Example program code: Java public Integer GetXPosition(){ return XPosition; } public Integer GetYPosition(){ return YPosition; } VB.NET Function GetXPosition() Return XPosition End Function Function GetYPosition() Return YPosition End Function Python def GetXPosition(self): return self. XPosition def GetYPosition(self): return self. YPosition

3(a)(iii)

XPosition = 0 End If End Function Function SetYPosition(Value) YPosition = YPosition + Value If YPosition > 10000 Then YPosition = 10000 ElseIf YPosition < 0 Then YPosition = 0 End If End Function Python def SetXPosition(self, Value): self. XPosition = self. XPosition + Value if(self.XPosition > 10000): self.XPosition = 10000 elif self.XPosition < 0: self.XPosition = 0 def SetYPosition(self, Value): self.YPosition = self.YPosition + Value if(self.YPosition > 10000): self.YPosition = 10000 elif self.YPosition < 0: self.YPosition = 0

3(a)(iv)

Python def Move(self, Direction): if(Direction == "up"): self.SetYPosition(10) elif(Direction == "down"): self.SetYPosition(-10) elif(Direction == "right"): self.SetXPosition(10) else: self.SetXPosition(-10)

3(b) [2 marks]

One mark each • New instance of created with identifier … Character Jack • … correct constructor called and values passed Example program code: Java Character Jack = new Character(50, 50, "Jack"); VB.NET Dim Jack As Character = New Character(50, 50, "Jack") Python Jack = Character(50, 50, "Jack")

3(c)(i) [3 marks]

One mark each • Class header inheriting from Character • Constructor taking all 3 parameters … • … calling parent/super constructor with the 3 parameters Example program code: Java class BikeCharacter extends Character{ public BikeCharacter(Integer XPositionP, Integer YPositionP, String NameP){ super(XPositionP, YPositionP, NameP); } } VB.NET Class BikeCharacter Inherits Character Sub New(XPositionP, YPositionP, NameP) MyBase.New(XPositionP, YPositionP, NameP) End Sub End Class Python class BikeCharacter(Character): def init (self, XPositionP, YPositionP, NameP): super(). init (XPositionP, YPositionP, NameP)

3(c)(ii)

Python def Move(self, Direction): if(Direction == "up"): super().SetYPosition(20) elif(Direction == "down"): super().SetYPosition(-20) elif(Direction == "right"): super().SetXPosition(2) else: super().SetXPosition(-20)

3(d) [1 mark]

One mark each • Declaring new with correct values e.g. BikeCharacter Java BikeCharacter Karla = new BikeCharacter(100, 50, "Karla"); VB.NET Dim Karla As BikeCharacter = New BikeCharacter(100, 50, "Karla") Python Karla = BikeCharacter(100, 50, "Karla")

3(e)(i)

Python CharacterToMove = input("Would you like to move Jack or Karla?").lower() while CharacterToMove != "jack" and CharacterToMove != "karla": CharacterToMove = input("Invalid try again") Direction = input("Which direction? Up, down, left or right?") while Direction != "up" and Direction != "down" and Direction != "left" and Direction != "right": Direction = input("Invalid try again") if CharacterToMove == "jack": Jack.Move(Direction) print("Jack's new position is X =", Jack.GetXPosition(), "Y =", Jack.GetYPosition()) else: Karla.Move(Direction) print("Karla's new position is X =", Karla.GetXPosition(), "Y =", Karla.GetYPosition())

3(e)(ii) [2 marks]

One mark for each test

Q3
Oct/Nov 2023 Paper 4 v2

A computer game is written using object-oriented programming.

The game has multiple characters.

The class Character stores data about the game characters. Each character has a name, date of birth, intelligence value and speed value. Character
Character Character
CharacterName : STRING
DateOfBirth : DATE
Intelligence : REAL
Speed : INTEGER
stores the name of the character
stores the date of birth of the character
stores the intelligence value of the character
stores the speed value of the character
Constructor()
SetIntelligence()
GetIntelligence()
GetName()
ReturnAge()
Learn()
initialisesCharacterName, DateOfBirth,
Intelligence andSpeed to the parameter values
assigns the value of the parameter toIntelligence
returns the value ofIntelligence
returns the name of the character
calculates and returns the age of the character as an integer
increases the value ofIntelligence by 10%

(a) (i) Write program code to declare the class Character and its constructor. 5 marks

Do not declare the other methods.

Use your programming language’s appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program as Question3_N23 .

Copy and paste the program code into part 3(a)(i) in the evidence document.

(ii) The get methods GetIntelligence() and GetName() return the attribute values. 3 marks

Write program code for the methods GetIntelligence() and GetName() .

Save your program.

Copy and paste the program code into part 3(a)(ii) in the evidence document.

(iii) The method SetIntelligence() assigns the value of its parameter to the attribute. 2 marks

Write program code for SetIntelligence() .

Save your program.

Copy and paste the program code into part 3(a)(iii) in the evidence document.

(iv) The method Learn() increases the current value of Intelligence by 10%. 1 mark

Write program code for Learn() .

Save your program.

Copy and paste the program code into part 3(a)(iv) in the evidence document.

(v) The method ReturnAge() calculates and returns the age of the character in years as an integer. 2 marks

Assume that the current year is 2023 and only use the year from the date of birth for the calculation. For example, the method returns 18 if the character was born on any date in 2005. Write program code for the method ReturnAge() .

Save your program.

Copy and paste the program code into part 3(a)(v) in the evidence document. (b) (i) Write program code to create a new instance of Character with the identifier 2 marks FirstCharacter .

The name of the character is Royal, date of birth is 1 January 2019, intelligence is 70 and speed is 30.

Save your program.

Copy and paste the program code into part 3(b)(i) in the evidence document.

(ii) Write program code to call the method Learn() for the character created in part 3(b)(i) . 3 marks

Output the name, age and intelligence of the character in an appropriate message.

Save your program.

Copy and paste the program code into part 3(b)(ii) in the evidence document.

(iii) Test your program. 1 mark

Take a screenshot of the output.

Save your program.

Copy and paste the screenshot into part 3(b)(iii) in the evidence document.

(c) The class MagicCharacter inherits from the class Character . A magic character has an

element, for example, water. This element changes how they learn. The magic character’s element is stored in the additional attribute Element. MagicCharacter
MagicCharacter MagicCharacter
Element : STRING stores the element for the character
Constructor()
Learn()
takesElement, CharacterName, DateOfBirth,
Intelligence andSpeed as parameters
calls its parent class constructor with the appropriate values
initialisesElement to its parameter value

alters the intelligence of the character depending on the
character’s element

(i) Write program code to declare the class MagicCharacter and its constructor. 5 marks

Do not declare the other method.

Use your programming language’s appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program.

Copy and paste the program code into part 3(c)(i) in the evidence document.

(ii) The method Learn() overrides the parent class method and increases the intelligence depending on the character’s element. 3 marks

  • If the element is fire or water, intelligence increases by 20%.

  • If the element is earth, intelligence increases by 30%.

  • If the element is not fire, water or earth the intelligence increases by 10%.

Write program code for Learn() .

Save your program.

Copy and paste the program code into part 3(c)(ii) in the evidence document. (d) (i) Write program code to create a new instance of MagicCharacter with the identifier 2 marks FirstMagic .

The name of the character is Light, date of birth is 3 March 2018, intelligence is 75, speed is 22 and element is fire.

Save your program.

Copy and paste the program code into part 3(d)(i) in the evidence document.

(ii) Write program code to call the method Learn() for the character created in part 3(d)(i) . 1 mark

Output the name, age and intelligence of the character in an appropriate message.

Save your program.

Copy and paste the program code into part 3(d)(ii) in the evidence document.

(iii) Test your program. 1 mark

Take a screenshot of the output.

Save your program.

Copy and paste the screenshot into part 3(d)(iii) in the evidence document.

A computer game is written using object-oriented programming. The game has multiple characters. |The class Character stores data about the game characters. Each character has a name, date of birth, intelligence value and speed value. Character|| |---|---| |**`Character`**|**`Character`**| |`CharacterName : STRING`<br>`DateOfBirth : DATE`<br>`Intelligence : REAL`<br>`Speed : INTEGER`|stores the name of the character<br>stores the date of birth of the character<br>stores the intelligence value of the character<br>stores the speed value of the character| |`Constructor()`<br>`SetIntelligence()`<br>`GetIntelligence()`<br>`GetName()`<br>`ReturnAge()`<br>`Learn()`|initialises`CharacterName`, `DateOfBirth`, <br>`Intelligence` and`Speed` to the parameter values<br>assigns the value of the parameter to`Intelligence`<br>returns the value of`Intelligence`<br>returns the name of the character<br>calculates and returns the age of the character as an integer<br>increases the value of`Intelligence` by 10%| **(a) (i)** Write program code to declare the class `Character` and its constructor. <span class="part-marks">5 marks</span> Do **not** declare the other methods. Use your programming language’s appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program as **Question3_N23** . Copy and paste the program code into part **3(a)(i)** in the evidence document. #### (ii) The get methods `GetIntelligence()` and `GetName()` return the attribute values. <span class="part-marks">3 marks</span> Write program code for the methods `GetIntelligence()` and `GetName()` . Save your program. Copy and paste the program code into part **3(a)(ii)** in the evidence document. #### (iii) The method `SetIntelligence()` assigns the value of its parameter to the attribute. <span class="part-marks">2 marks</span> Write program code for `SetIntelligence()` . Save your program. Copy and paste the program code into part **3(a)(iii)** in the evidence document. #### (iv) The method `Learn()` increases the current value of `Intelligence` by 10%. <span class="part-marks">1 mark</span> Write program code for `Learn()` . Save your program. Copy and paste the program code into part **3(a)(iv)** in the evidence document. #### (v) The method `ReturnAge()` calculates and returns the age of the character in years as an integer. <span class="part-marks">2 marks</span> Assume that the current year is 2023 and **only** use the year from the date of birth for the calculation. For example, the method returns 18 if the character was born on any date in 2005. Write program code for the method `ReturnAge()` . Save your program. Copy and paste the program code into part **3(a)(v)** in the evidence document. **(b) (i)** Write program code to create a new instance of `Character` with the identifier <span class="part-marks">2 marks</span> `FirstCharacter` . The name of the character is Royal, date of birth is 1 January 2019, intelligence is 70 and speed is 30. Save your program. Copy and paste the program code into part **3(b)(i)** in the evidence document. #### (ii) Write program code to call the method `Learn()` for the character created in part **3(b)(i)** . <span class="part-marks">3 marks</span> Output the name, age and intelligence of the character in an appropriate message. Save your program. Copy and paste the program code into part **3(b)(ii)** in the evidence document. #### (iii) Test your program. <span class="part-marks">1 mark</span> Take a screenshot of the output. Save your program. Copy and paste the screenshot into part **3(b)(iii)** in the evidence document. ### (c) The class `MagicCharacter` inherits from the class `Character` . A magic character has an |element, for example, water. This element changes how they learn. The magic character’s element is stored in the additional attribute Element. MagicCharacter|| |---|---| |**`MagicCharacter`**|**`MagicCharacter`**| |`Element : STRING`|stores the element for the character| |`Constructor()`<br>`Learn()`|takes`Element`, `CharacterName`, `DateOfBirth`, <br>`Intelligence` and`Speed` as parameters<br>calls its parent class constructor with the appropriate values<br>initialises`Element` to its parameter value<br> <br>alters the intelligence of the character depending on the<br>character’s element| #### (i) Write program code to declare the class `MagicCharacter` and its constructor. <span class="part-marks">5 marks</span> Do **not** declare the other method. Use your programming language’s appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into part **3(c)(i)** in the evidence document. #### (ii) The method `Learn()` overrides the parent class method and increases the intelligence depending on the character’s element. <span class="part-marks">3 marks</span> - If the element is fire or water, intelligence increases by 20%. - If the element is earth, intelligence increases by 30%. - If the element is not fire, water or earth the intelligence increases by 10%. Write program code for `Learn()` . Save your program. Copy and paste the program code into part **3(c)(ii)** in the evidence document. **(d) (i)** Write program code to create a new instance of `MagicCharacter` with the identifier <span class="part-marks">2 marks</span> `FirstMagic` . The name of the character is Light, date of birth is 3 March 2018, intelligence is 75, speed is 22 and element is fire. Save your program. Copy and paste the program code into part **3(d)(i)** in the evidence document. #### (ii) Write program code to call the method `Learn()` for the character created in part **3(d)(i)** . <span class="part-marks">1 mark</span> Output the name, age and intelligence of the character in an appropriate message. Save your program. Copy and paste the program code into part **3(d)(ii)** in the evidence document. #### (iii) Test your program. <span class="part-marks">1 mark</span> Take a screenshot of the output. Save your program. Copy and paste the screenshot into part **3(d)(iii)** in the evidence document.
Show mark scheme

3(a)(i)

Speed = SpeedP End Sub End Class Python class Character: #self.__CharacterName string #self.__DateOfBirth date #self.__Intelligence real #self.__Speed integer def init(self, CName, DBirth, Intell, SpeedP): self.__CharacterName = CName self.__DateOfBirth = DBirth self.__Intelligence = Intell self.__Speed = SpeedP

3(a)(ii) [3 marks]

One mark each: • 1 get header with no parameter … • … returning attribute • Second correct get method Example program code: Java public Double GetIntelligence(){ return Intelligence; } public String GetName(){ return CharacterName; } VB.NET Function GetIntelligence() Return Intelligence End Function Function GetName() Return CharacterName End Function Python def GetIntelligence(self): return self.__Intelligence def GetName(self): return self.__CharacterName

3(a)(iii) [2 marks]

One mark each • Set header with 1 parameter … • … assigns parameter to attribute Example program code: Java public void SetIntelligence(Double NewValue){ Intelligence = NewValue; } VB.NET Sub SetIntelligence(NewValue) Intelligence = NewValue End Sub+ Python def SetIntelligence(self, NewValue): self.__Intelligence = NewValue

3(a)(iv) [1 mark]

One mark for method multiplying attribute intelligence by 1.1 (or equivalent) and storing in Example program code: Java public void Learn(){ Intelligence = Intelligence * 1.1; } VB.NET Overridable Sub Learn() Intelligence = Intelligence * 1.1 End Sub Python def Learn(self): self.__Intelligence = self.__Intelligence * 1.1

3(a)(v) [2 marks]

One mark each • Method (function) header (and end where appropriate) no parameter, returning a calculated age • Extracting attribute year of birth from date and subtracting from 2023 Example program code: Java public Integer ReturnAge(){ return 2023 - DateOfBirth.getYear(); } VB.NET Function ReturnAge() Return DateDiff(DateInterval.Year, DateOfBirth, #01/01/2023#) End Function Python def ReturnAge(self): return 2023 - self.__DateOfBirth.year

3(b)(i) [2 marks]

One mark each: • Creating new instance of with identifier Character FirstCharacter • … sending correct values as parameters Example program code: Java Character FirstCharacter = new Character("Royal", new Date(2019,01,01), 70.0, 30); VB.NET Sub Main(args As String()) Dim FirstCharacter As Character FirstCharacter = New Character("Royal", #1/1/2019#, 70, 30) End Sub Python FirstCharacter = Character("Royal", datetime.datetime(2019, 1, 1), 70, 30)

3(b)(ii) [1 mark]

One mark each • Calling for Learn() FirstCharacter • Calling and outputting return value ReturnAge() • Outputting name and intelligence using gets with suitable message Example program code: Java FirstCharacter.Learn(); System.out.println(FirstCharacter.GetName() + " is " + FirstCharacter.ReturnAge() + " years old and has intelligence " + FirstCharacter.GetIntelligence()); VB.NET FirstCharacter.Learn() Console.WriteLine(FirstCharacter.GetName() & " is " & FirstCharacter.ReturnAge() & " years old and has intelligence " & FirstCharacter.GetIntelligence()) Python FirstCharacter.Learn() print(FirstCharacter.GetName(), "is", FirstCharacter.ReturnAge(), "years old and has intelligence" , FirstCharacter.GetIntelligence()) One mark for screenshot with Royal, 4 years, 77 intelligence e.g.

3(c)(i)

Python class MagicCharacter(Character): #self.__Element String def init(self, ElementP, CName, DBirth, Intell, SpeedP): super().init(CName, DBirth, Intell, SpeedP) self.__Element = ElementP

3(c)(ii)

Python def Learn(self): if(self.__Element == "fire" or self.__Element == "water"): super().SetIntelligence(super().GetIntelligence() * 1.2) elif self.__Element == "earth": super().SetIntelligence(super().GetIntelligence() * 1.3) else: super().SetIntelligence(super().GetIntelligence() * 1.1)

3(d)(i) [2 marks]

One mark each: • Declaring with identifier … MagicCharacter FirstMagic • … with correct parameters Example program code: Java MagicCharacter FirstMagic = new MagicCharacter("fire", "Light", new Date(2018,03,03), 75.0, 22); VB.NET Dim FirstMagic As MagicCharacter FirstMagic = New MagicCharacter("fire", "Light", #3/3/2018#, 75, 22) Python FirstMagic = MagicCharacter("fire", "Light", datetime.datetime(2018, 3, 3), 75, 22)

3(d)(ii) [1 mark]

One mark for calling for and outputting all required data in appropriate message using gets. Learn() FirstMagic Example program code: Java FirstMagic.Learn(); System.out.println(FirstMagic.GetName() + " is " + FirstMagic.ReturnAge() + " years old and has intelligence " + FirstMagic.GetIntelligence()); VB.NET FirstMagic.Learn() Console.WriteLine(FirstMagic.GetName() & " is " & FirstMagic.ReturnAge() & " years old and has intelligence " & FirstMagic.GetIntelligence()) Python FirstMagic.Learn() print(FirstMagic.GetName(), "is", FirstMagic.ReturnAge(), "years old and has intelligence", FirstMagic.GetIntelligence())

3(d)(iii) [1 mark]

One mark for screenshot e.g.

Q3
Oct/Nov 2023 Paper 4 v3

A computer game is written using object-oriented programming.

The game has multiple characters that can move around the screen.

The class Character stores data about the characters. Each character has a name, a curren (horizontal) position and a current Y (vertical) position.
Character Character
Name : STRING
XPosition : INTEGER
YPosition : INTEGER
stores the name of the character as a string
stores the X position as an integer
stores the Y position as an integer
Constructor()
GetXPosition()
GetYPosition()
SetXPosition()
SetYPosition()
Move()
initialisesName, XPosition andYPosition to its
parameter values
returns the X position
returns the Y position
adds the parameter to the X position
validates that the new X position is between 0 and 10 000
inclusive
adds the parameter to the Y position
validates that the new Y position is between 0 and 10 000
inclusive
takes a direction as a parameter and calls either
SetXPosition orSetYPosition with an integer value

(a) (i) Write program code to declare the class Character and its constructor. 4 marks

Do not declare the other methods.

Use your programming language’s appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program as Question3_N23 .

Copy and paste the program code into part 3(a)(i) in the evidence document.

(ii) The get methods GetXPosition() and GetYPosition() each return the relevant attribute. 3 marks

Write program code for the get methods.

Save your program.

Copy and paste the program code into part 3(a)(ii) in the evidence document.

(iii) The set methods SetXPosition() and SetYPosition() each take a value as a parameter and add this to the current X or Y position. 4 marks

If the new value exceeds 10 000, it is limited to 10 000.

If the new value is below 0, it is limited to 0.

Write program code for the set methods.

Save your program.

Copy and paste the program code into part 3(a)(iii) in the evidence document.

(iv) The method Move() takes a string parameter: "up", "down", "left" or "right" . 4 marks

The table shows the change each direction will make to the X or Y position.

Use the appropriate method to change the position value.

Direction Value change
up Y position + 10
down Y position − 10
left X position − 10
right X position + 10

Write program code for Move() .

Save your program.

Copy and paste the program code into part 3(a)(iv) in the evidence document.

(b) Write program code to declare a new instance of Character with the identifier Jack . 2 marks

The starting X position is 50 and the starting Y position is 50, the character’s name is Jack.

Save your program.

Copy and paste the program code into part 3(b) in the evidence document.

(c) The class BikeCharacter inherits from the class Character.
BikeCharacter BikeCharacter
Constructor()
Move()
takesName, XPosition andYPosition as parameters
calls its parent class constructor with the appropriate values
overrides the methodMove() from the parent class by
changing either the X position or the Y position by 20
instead of 10

(i) Write program code to declare the class BikeCharacter and its constructor. 3 marks

Do not declare the other method.

Use your programming language’s appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program.

Copy and paste the program code into part 3(c)(i) in the evidence document.

(ii) The method Move() overrides the method from the parent class. 2 marks

The table shows the change each direction will make to the X or Y position.

Direction Value change
up Y position + 20
down Y position − 20
left X position − 20
right X position + 20

Write program code for Move() .

Save your program.

Copy and paste the program code into part 3(c)(ii) in the evidence document.

(d) Write program code to declare a new instance of BikeCharacter with the identifier Karla . 1 mark

The starting X position is 100, the starting Y position is 50 and the character’s name is Karla.

Save your program.

Copy and paste the program code into part 3(d) in the evidence document. (e) (i) Write program code to: 5 marks

  • take as input which of the two characters the user would like to move

  • take as input the direction the user would like the character to move

  • call the appropriate method to move the character

  • output the character’s new X and Y position in an appropriate format, for example:

          "Karla's new position is X = 100 Y = 200"

All inputs require appropriate prompts and must be validated.

Save your program.

Copy and paste the program code into part 3(e)(i) in the evidence document.

(ii) Test your program twice with the following inputs. 2 marks

Test 1: jack right

Test 2: karla down

Take a screenshot of the output.

Save your program.

Copy and paste the screenshot into part 3(e)(ii) in the evidence document.

A computer game is written using object-oriented programming. The game has multiple characters that can move around the screen. |The class Character stores data about the characters. Each character has a name, a curren (horizontal) position and a current Y (vertical) position.|| |---|---| |**`Character`**|**`Character`**| |`Name : STRING`<br>`XPosition : INTEGER`<br>`YPosition : INTEGER`|stores the name of the character as a string<br>stores the X position as an integer<br>stores the Y position as an integer| |`Constructor()`<br>`GetXPosition()`<br>`GetYPosition()`<br>`SetXPosition()`<br>`SetYPosition()`<br>`Move()`|initialises`Name`, `XPosition` and`YPosition` to its<br>parameter values<br>returns the X position<br>returns the Y position<br>adds the parameter to the X position<br>validates that the new X position is between 0 and 10 000<br>inclusive<br>adds the parameter to the Y position<br>validates that the new Y position is between 0 and 10 000<br>inclusive<br>takes a direction as a parameter and calls either<br>`SetXPosition` or`SetYPosition` with an integer value| **(a) (i)** Write program code to declare the class `Character` and its constructor. <span class="part-marks">4 marks</span> Do **not** declare the other methods. Use your programming language’s appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program as **Question3_N23** . Copy and paste the program code into part **3(a)(i)** in the evidence document. #### (ii) The get methods `GetXPosition()` and `GetYPosition()` each return the relevant attribute. <span class="part-marks">3 marks</span> Write program code for the get methods. Save your program. Copy and paste the program code into part **3(a)(ii)** in the evidence document. #### (iii) The set methods `SetXPosition()` and `SetYPosition()` each take a value as a parameter and add this to the current X or Y position. <span class="part-marks">4 marks</span> If the new value exceeds 10 000, it is limited to 10 000. If the new value is below 0, it is limited to 0. Write program code for the set methods. Save your program. Copy and paste the program code into part **3(a)(iii)** in the evidence document. #### (iv) The method `Move()` takes a string parameter: `"up"`, `"down"`, `"left"` or `"right"` . <span class="part-marks">4 marks</span> The table shows the change each direction will make to the X or Y position. Use the appropriate method to change the position value. |Direction|Value change| |---|---| |up|Y position + 10| |down|Y position − 10| |left|X position − 10| |right|X position + 10| Write program code for `Move()` . Save your program. Copy and paste the program code into part **3(a)(iv)** in the evidence document. ### (b) Write program code to declare a new instance of `Character` with the identifier `Jack` . <span class="part-marks">2 marks</span> The starting X position is 50 and the starting Y position is 50, the character’s name is Jack. Save your program. Copy and paste the program code into part **3(b)** in the evidence document. |(c) The class BikeCharacter inherits from the class Character.|| |---|---| |**`BikeCharacter`**|**`BikeCharacter`**| |`Constructor()`<br>`Move()`|takes`Name`, `XPosition` and`YPosition` as parameters<br>calls its parent class constructor with the appropriate values<br>overrides the method`Move()` from the parent class by<br>changing either the X position or the Y position by 20<br>instead of 10| #### (i) Write program code to declare the class `BikeCharacter` and its constructor. <span class="part-marks">3 marks</span> Do **not** declare the other method. Use your programming language’s appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into part **3(c)(i)** in the evidence document. #### (ii) The method `Move()` overrides the method from the parent class. <span class="part-marks">2 marks</span> The table shows the change each direction will make to the X or Y position. |Direction|Value change| |---|---| |up|Y position + 20| |down|Y position − 20| |left|X position − 20| |right|X position + 20| Write program code for `Move()` . Save your program. Copy and paste the program code into part **3(c)(ii)** in the evidence document. ### (d) Write program code to declare a new instance of `BikeCharacter` with the identifier `Karla` . <span class="part-marks">1 mark</span> The starting X position is 100, the starting Y position is 50 and the character’s name is Karla. Save your program. Copy and paste the program code into part **3(d)** in the evidence document. **(e) (i)** Write program code to: <span class="part-marks">5 marks</span> - take as input which of the two characters the user would like to move - take as input the direction the user would like the character to move - call the appropriate method to move the character - output the character’s new X and Y position in an appropriate format, for example: ``` "Karla's new position is X = 100 Y = 200" ``` All inputs require appropriate prompts and must be validated. Save your program. Copy and paste the program code into part **3(e)(i)** in the evidence document. #### (ii) Test your program twice with the following inputs. <span class="part-marks">2 marks</span> Test 1: jack right Test 2: karla down Take a screenshot of the output. Save your program. Copy and paste the screenshot into part **3(e)(ii)** in the evidence document.
Show mark scheme

3(a)(i)

Python class Character: #self.XPosition integer #self.YPosition integer #self.Name string def init (self, XPositionP, YPositionP, NameP): self.XPosition = XPositionP self.YPosition = YPositionP self.Name = NameP

3(a)(ii) [3 marks]

One mark each • 1 get header with no parameter … • … returning correct value • 2nd get method Example program code: Java public Integer GetXPosition(){ return XPosition; } public Integer GetYPosition(){ return YPosition; } VB.NET Function GetXPosition() Return XPosition End Function Function GetYPosition() Return YPosition End Function Python def GetXPosition(self): return self. XPosition def GetYPosition(self): return self. YPosition

3(a)(iii)

XPosition = 0 End If End Function Function SetYPosition(Value) YPosition = YPosition + Value If YPosition > 10000 Then YPosition = 10000 ElseIf YPosition < 0 Then YPosition = 0 End If End Function Python def SetXPosition(self, Value): self. XPosition = self. XPosition + Value if(self.XPosition > 10000): self.XPosition = 10000 elif self.XPosition < 0: self.XPosition = 0 def SetYPosition(self, Value): self.YPosition = self.YPosition + Value if(self.YPosition > 10000): self.YPosition = 10000 elif self.YPosition < 0: self.YPosition = 0

3(a)(iv)

Python def Move(self, Direction): if(Direction == "up"): self.SetYPosition(10) elif(Direction == "down"): self.SetYPosition(-10) elif(Direction == "right"): self.SetXPosition(10) else: self.SetXPosition(-10)

3(b) [2 marks]

One mark each • New instance of created with identifier … Character Jack • … correct constructor called and values passed Example program code: Java Character Jack = new Character(50, 50, "Jack"); VB.NET Dim Jack As Character = New Character(50, 50, "Jack") Python Jack = Character(50, 50, "Jack")

3(c)(i) [3 marks]

One mark each • Class header inheriting from Character • Constructor taking all 3 parameters … • … calling parent/super constructor with the 3 parameters Example program code: Java class BikeCharacter extends Character{ public BikeCharacter(Integer XPositionP, Integer YPositionP, String NameP){ super(XPositionP, YPositionP, NameP); } } VB.NET Class BikeCharacter Inherits Character Sub New(XPositionP, YPositionP, NameP) MyBase.New(XPositionP, YPositionP, NameP) End Sub End Class Python class BikeCharacter(Character): def init (self, XPositionP, YPositionP, NameP): super(). init (XPositionP, YPositionP, NameP)

3(c)(ii)

Python def Move(self, Direction): if(Direction == "up"): super().SetYPosition(20) elif(Direction == "down"): super().SetYPosition(-20) elif(Direction == "right"): super().SetXPosition(2) else: super().SetXPosition(-20)

3(d) [1 mark]

One mark each • Declaring new with correct values e.g. BikeCharacter Java BikeCharacter Karla = new BikeCharacter(100, 50, "Karla"); VB.NET Dim Karla As BikeCharacter = New BikeCharacter(100, 50, "Karla") Python Karla = BikeCharacter(100, 50, "Karla")

3(e)(i)

Python CharacterToMove = input("Would you like to move Jack or Karla?").lower() while CharacterToMove != "jack" and CharacterToMove != "karla": CharacterToMove = input("Invalid try again") Direction = input("Which direction? Up, down, left or right?") while Direction != "up" and Direction != "down" and Direction != "left" and Direction != "right": Direction = input("Invalid try again") if CharacterToMove == "jack": Jack.Move(Direction) print("Jack's new position is X =", Jack.GetXPosition(), "Y =", Jack.GetYPosition()) else: Karla.Move(Direction) print("Karla's new position is X =", Karla.GetXPosition(), "Y =", Karla.GetYPosition())

3(e)(ii) [2 marks]

One mark for each test

Q4
May/Jun 2023 Paper 3 v2

Draw one line from each Object‑Oriented Programming (OOP) term to its most appropriate description.

OOP term Description

Encapsulation

Getters

Polymorphism

Setters

methods used to return the value of a property

the process of putting data and methods together as a single unit

methods used to update the value of a property

allows methods to be redefined for derived classes

enables the defining of a new class that inherits from a parent class 4 marks

Draw **one** line from each Object‑Oriented Programming (OOP) term to its **most appropriate** description. **OOP term** **Description** Encapsulation Getters Polymorphism Setters methods used to return the value of a property the process of putting data and methods together as a single unit methods used to update the value of a property allows methods to be redefined for derived classes enables the defining of a new class that inherits from a parent class <span class="part-marks">4 marks</span>
Show mark scheme

4 [2 marks]

One mark for each correct line connecting an OOP term to its description (Max 4) . OOP term Description methods used to return the value of a property Encapsulation the process of putting data and methods together as a single unit Getters methods used to update the value of a property Polymorphism allows methods to be redefined for derived classes Setters enables the defining of a new class that inherits from a parent class

Q2
May/Jun 2023 Paper 4 v1

A computer game is being designed that will include different vehicles. A prototype for the game is being developed using object‑oriented programming.

The class Vehicle stores data about the vehicles. Each vehicle has an identification name, a maximum speed, a current speed and a horizontal position. The value IncreaseAmount is added to the current speed each time the vehicle increases its speed.

Vehicle
ID : STRING
MaxSpeed : INTEGER
CurrentSpeed : INTEGER
IncreaseAmount : INTEGER
HorizontalPosition : INTEGER
stores the identification name for the vehicle
stores the maximum speed
stores the current speed
stores the amountCurrentSpeed increases by
stores the horizontal position
Constructor()
GetCurrentSpeed()
GetIncreaseAmount()
GetHorizontalPosition()
GetMaxSpeed()
SetCurrentSpeed()
SetHorizontalPosition()
IncreaseSpeed()
initialisesID, MaxSpeed andIncreaseAmount to the
parameter values
initialises bothCurrentSpeed and
HorizontalPosition to0
returns the current speed
returns the increase amount
returns the horizontal position
returns the maximum speed
assigns the parameter to the current speed
assigns the parameter to the horizontal position
calculates and stores the new speed and horizontal
position of the vehicle

(a) (i) Write program code to declare the class Vehicle . All attributes must be private. 5 marks

You only need to declare the class and its constructor. Do not declare any other methods.

Use your programming language’s appropriate constructor.

If you are writing program code in Python, include attribute declarations using comments.

Save your program as Question2_J2023 .

Copy and paste the program code into part 2(a)(i) in the evidence document.

(ii) Write program code for the get methods GetCurrentSpeed(), GetIncreaseAmount(), GetMaxSpeed() and GetHorizontalPosition() Save your program. 3 marks

Copy and paste the program code into part 2(a)(ii) in the evidence document.

(iii) Write program code for the set methods SetCurrentSpeed() and 3 marks

      SetHorizontalPosition()

Save your program.

Copy and paste the program code into part 2(a)(iii) in the evidence document.

(iv) The method IncreaseSpeed() : 3 marks

  • adds IncreaseAmount to the current speed

  • adds the updated current speed to the horizontal position.

The current speed of a vehicle cannot exceed its maximum speed.

Write program code for the method IncreaseSpeed()

Save your program.

Copy and paste the program code into part 2(a)(iv) in the evidence document.

(b) The child class Helicopter inherits from the parent class Vehicle. A helicopter also has a vertical position and changes the vertical position when it increases speed. Helicopter
Helicopter Helicopter
VerticalPosition : INTEGER
VerticalChange : INTEGER
MaxHeight : INTEGER
stores the vertical position
stores the amountVerticalPosition changes by
stores the maximum height the helicopter can reach
Constructor()
GetVerticalPosition()
IncreaseSpeed()
takes the ID, maximum speed, increase amount, vertical
change and maximum height as parameters
initialises the vertical position to 0
returns the vertical position
changes the current speed, horizontal and vertical
position of the helicopter

(i) Write program code to declare the class Helicopter . You only need to declare the class and its constructor. You do not need to declare the other methods. 5 marks

Use your programming language’s appropriate constructor.

All attributes must be private.

If you are writing in Python, include attribute declarations using comments.

Save your program.

Copy and paste the program code into part 2(b)(i) in the evidence document.

(ii) The Helicopter method IncreaseSpeed() overrides the method from the parent class and: 4 marks

  • adds the amount of vertical change to the vertical position

  • adds IncreaseAmount to the current speed

  • adds the updated current speed to the horizontal position.

The vertical position of a helicopter cannot exceed its maximum height.

The current speed of a helicopter cannot exceed its maximum speed.

Write program code for the method IncreaseSpeed()

Save your program.

Copy and paste the program code into part 2(b)(ii) in the evidence document.

(c) A procedure needs to output the horizontal position and speed of a vehicle. If the vehicle is a helicopter, it also outputs the vertical position. 3 marks

All outputs must include appropriate messages.

Write program code for this procedure.

Save your program.

Copy and paste the program code into part 2(c) in the evidence document.

(d) The main program needs to:

  • instantiate a car as a new vehicle with the ID "Tiger", a maximum speed of 100 and an increase amount of 20

  • instantiate a new helicopter with the ID "Lion", a maximum speed of 350, an increase amount of 40, a vertical change of 3 and a maximum height of 100

  • call IncreaseSpeed() twice for the car and then call the output procedure from part 2(c) for the car

  • call IncreaseSpeed() twice for the helicopter and then call the output procedure from part 2(c) for the helicopter.

(i) Write program code for the main program. 5 marks

Save your program.

Copy and paste the program code into part 2(d)(i) in the evidence document.

(ii) Test your program. 1 mark

Take a screenshot of the output.

Save your program.

Copy and paste the screenshot into part 2(d)(ii) in the evidence document.

A computer game is being designed that will include different vehicles. A prototype for the game is being developed using object‑oriented programming. The class `Vehicle` stores data about the vehicles. Each vehicle has an identification name, a maximum speed, a current speed and a horizontal position. The value `IncreaseAmount` is added to the current speed each time the vehicle increases its speed. |Vehicle|| |---|---| |`ID : STRING`<br>`MaxSpeed : INTEGER`<br>`CurrentSpeed : INTEGER`<br>`IncreaseAmount : INTEGER`<br>`HorizontalPosition : INTEGER`|stores the identification name for the vehicle<br>stores the maximum speed<br>stores the current speed<br>stores the amount`CurrentSpeed` increases by<br>stores the horizontal position| |`Constructor()`<br>`GetCurrentSpeed()`<br>`GetIncreaseAmount()`<br>`GetHorizontalPosition()`<br>`GetMaxSpeed()`<br>`SetCurrentSpeed()`<br>`SetHorizontalPosition()`<br>`IncreaseSpeed()`|initialises`ID`, `MaxSpeed` and`IncreaseAmount` to the<br>parameter values<br>initialises both`CurrentSpeed` and<br>`HorizontalPosition` to`0`<br>returns the current speed<br>returns the increase amount<br>returns the horizontal position<br>returns the maximum speed<br>assigns the parameter to the current speed<br>assigns the parameter to the horizontal position<br>calculates and stores the new speed and horizontal<br>position of the vehicle| **(a) (i)** Write program code to declare the class `Vehicle` . All attributes must be private. <span class="part-marks">5 marks</span> You only need to declare the class and its constructor. Do not declare any other methods. Use your programming language’s appropriate constructor. If you are writing program code in Python, include attribute declarations using comments. Save your program as **Question2_J2023** . Copy and paste the program code into **part 2(a)(i)** in the evidence document. #### (ii) Write program code for the get methods `GetCurrentSpeed()`, `GetIncreaseAmount()`, `GetMaxSpeed()` and `GetHorizontalPosition()` Save your program. <span class="part-marks">3 marks</span> Copy and paste the program code into **part 2(a)(ii)** in the evidence document. #### (iii) Write program code for the set methods `SetCurrentSpeed()` and <span class="part-marks">3 marks</span> ``` SetHorizontalPosition() ``` Save your program. Copy and paste the program code into **part 2(a)(iii)** in the evidence document. #### (iv) The method `IncreaseSpeed()` : <span class="part-marks">3 marks</span> - adds `IncreaseAmount` to the current speed - adds the updated current speed to the horizontal position. The current speed of a vehicle cannot exceed its maximum speed. Write program code for the method `IncreaseSpeed()` Save your program. Copy and paste the program code into **part 2(a)(iv)** in the evidence document. |(b) The child class Helicopter inherits from the parent class Vehicle. A helicopter also has a vertical position and changes the vertical position when it increases speed. Helicopter|| |---|---| |**`Helicopter`**|**`Helicopter`**| |`VerticalPosition : INTEGER`<br>`VerticalChange : INTEGER`<br>`MaxHeight : INTEGER`|stores the vertical position<br>stores the amount`VerticalPosition` changes by<br>stores the maximum height the helicopter can reach| |`Constructor()`<br>`GetVerticalPosition()`<br>`IncreaseSpeed()`|takes the ID, maximum speed, increase amount, vertical<br>change and maximum height as parameters<br>initialises the vertical position to 0<br>returns the vertical position<br>changes the current speed, horizontal and vertical<br>position of the helicopter| #### (i) Write program code to declare the class `Helicopter` . You only need to declare the class and its constructor. You do not need to declare the other methods. <span class="part-marks">5 marks</span> Use your programming language’s appropriate constructor. All attributes must be private. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into **part 2(b)(i)** in the evidence document. #### (ii) The `Helicopter` method `IncreaseSpeed()` overrides the method from the parent class and: <span class="part-marks">4 marks</span> - adds the amount of vertical change to the vertical position - adds `IncreaseAmount` to the current speed - adds the updated current speed to the horizontal position. The vertical position of a helicopter cannot exceed its maximum height. The current speed of a helicopter cannot exceed its maximum speed. Write program code for the method `IncreaseSpeed()` Save your program. Copy and paste the program code into **part 2(b)(ii)** in the evidence document. ### (c) A procedure needs to output the horizontal position and speed of a vehicle. If the vehicle is a helicopter, it also outputs the vertical position. <span class="part-marks">3 marks</span> All outputs must include appropriate messages. Write program code for this procedure. Save your program. Copy and paste the program code into **part 2(c)** in the evidence document. ### (d) The main program needs to: - instantiate a car as a new vehicle with the ID "Tiger", a maximum speed of 100 and an increase amount of 20 - instantiate a new helicopter with the ID "Lion", a maximum speed of 350, an increase amount of 40, a vertical change of 3 and a maximum height of 100 - call `IncreaseSpeed()` twice for the car and then call the output procedure from **part 2(c)** for the car - call `IncreaseSpeed()` twice for the helicopter and then call the output procedure from **part 2(c)** for the helicopter. #### (i) Write program code for the main program. <span class="part-marks">5 marks</span> Save your program. Copy and paste the program code into **part 2(d)(i)** in the evidence document. #### (ii) Test your program. <span class="part-marks">1 mark</span> Take a screenshot of the output. Save your program. Copy and paste the screenshot into **part 2(d)(ii)** in the evidence document.
Show mark scheme

2(a)(i)

public Vehicle(String IDP, Integer MaxSpeedP, Integer IncreaseAmountP){ ID = IDP; MaxSpeed = MaxSpeedP; IncreaseAmount = IncreaseAmountP; CurrentSpeed = 0; HorizontalPosition = 0; }} Python class Vehicle: #self.__ID string #self.__MaxSpeed integer #self.__CurrentSpeed integer #self.__IncreaseAmount integer #self.__HorizontalPosition def init(self, IDP, MaxSpeedP, IncreaseAmountP): self.__ID = IDP self.__MaxSpeed = MaxSpeedP self.__IncreaseAmount = IncreaseAmountP self.__CurrentSpeed = 0 self.__HorizontalPosition = 0

2(a)(ii)

Python def GetCurrentSpeed(self): return self.__CurrentSpeed def GetIncreaseAmount(self): return self.__IncreaseAmount def GetHorizontalPosition(self): return self.__HorizontalPosition def GetMaxSpeed(self): return self.__MaxSpeed

2(a)(iii) [3 marks]

1 mark each 1 set procedure (and end where appropriate) taking parameter … … assigns parameter to the attribute (without overriding) Second correct set method Example program code: VB.NET Sub SetCurrentSpeed(CSp) CurrentSpeed = CSp End Sub Sub SetHorizontalPosition(HPP) HorizontalPosition = HPP End Sub public void SetCurrentSpeed(Integer CSP){ CurrentSpeed = CSP; public void SetHorizontalPosition(Integer HPP){ HorizontalPosition = HPP; Python def SetCurrentSpeed(self, CSP): self.__CurrentSpeed = CSP def SetHorizontalPosition(self, HPP): self.__HorizontalPosition = HPP

2(a)(iv) [3 marks]

1 mark each Method header (and close where appropriate) with no parameter and adding IncreaseAmount to CurrentSpeed Checking if MaxSpeed is exceeded and limiting to max speed (remove increase or assign maximum) Adding updated CurrentSpeed to HorizontalPosition in all cases (whether MaxSpeed is exceeded or not) Example program code: VB.NET Sub IncreaseSpeed() CurrentSpeed = CurrentSpeed + IncreaseAmount If CurrentSpeed > MaxSpeed Then CurrentSpeed = MaxSpeed End If HorizontalPosition = HorizontalPosition + CurrentSpeed End Sub public void IncreaseSpeed(){ CurrentSpeed = CurrentSpeed + IncreaseAmount; if(CurrentSpeed > MaxSpeed){ CurrentSpeed = MaxSpeed; } HorizontalPosition = HorizontalPosition + CurrentSpeed; Python def IncreaseSpeed(self): self.__CurrentSpeed = self.__CurrentSpeed + self.__IncreaseAmount if(self.__CurrentSpeed > self.__MaxSpeed): self.__CurrentSpeed = self.__MaxSpeed self.__HorizontalPosition = self.__HorizontalPosition + self.__CurrentSpeed

2(b)(i)

super(IDP, MaxSpeedP, IncreaseAmountP); VerticalPosition = 0; VerticalChange = VertChangeP; MaxHeight = MaxHeightP; }} Python class Helicopter(Vehicle): #VerticalPosition Integer #VerticalChange Integer #MaxHeight Integer def init(self, IDP, MaxSpeedP, IncreaseAmountP, VertChangeP, MaxHeightP): Vehicle.init(self,IDP, MaxSpeedP, IncreaseAmountP) self.__VerticalPosition = 0 self.__VerticalChange = VertChangeP self.__MaxHeight = MaxHeightP

2(b)(ii)

Python def IncreaseSpeed(self): self.__VerticalPosition = self.__VerticalPosition + self.__VerticalChange if(self.__VerticalPosition > self.__MaxHeight): self.__VerticalPosition = MaxHeight Vehicle.SetCurrentSpeed(self, Vehicle.GetCurrentSpeed(self) + Vehicle.GetIncreaseAmount(self)) if(Vehicle.GetCurrentSpeed(self) > Vehicle.GetMaxSpeed(self)): Vehicle.SetCurrentSpeed(self, Vehicle.GetMaxSpeed(self)); Vehicle.SetHorizontalPosition(self, Vehicle.GetHorizontalPosition(self) + Vehicle.GetCurrentSpeed(self))

2(c)

def OutputCurrentPosition(self): print("Current position = ", Vehicle.GetHorizontalPosition(self)) print("Current speed = ", Vehicle.GetCurrentSpeed(self)) print("Current verticalposition = ", self.__VerticalPosition)

2(d)(i)

Python #main Car = Vehicle("Tiger", 100, 20) Heli1 = Helicopter("Lion", 350, 40, 3, 100) Car.IncreaseSpeed() Car.IncreaseSpeed() Car.OutputCurrentPosition() print("") Heli1.IncreaseSpeed() Heli1.IncreaseSpeed() Heli1.OutputCurrentPosition()

2(d)(ii) [1 mark]

Screenshot of results e.g.

Q3
May/Jun 2023 Paper 4 v2

A company needs a computer program to store data about its employees.

Part of the program is being written using object‑oriented programming.

The class Employee stores data about the employees. Each employee has an employee number,

a job title and hourly pay rate. The class will also store the amount they are paid each week over a 52‑week year in a 1D array. Employee
Employee Employee
HourlyPay : REAL
EmployeeNumber : STRING
JobTitle : STRING
PayYear2022 : ARRAY[0:51] OF REAL
stores the amount each employee gets paid each
hour
stores the employee’s unique number
stores the employee’s job title
stores the amount the employee has been paid each
week
Constructor()
GetEmployeeNumber()
SetPay()
GetTotalPay()
initialisesHourlyPay, EmployeeNumber and
JobTitle from the values passed as parameters
initialises all 52 elements inPayYear2022 to0.0
returns the employee number
takes the week number and number of hours worked
that week as parameters
calculates and stores the pay for that week in
PayYear2022
returns the total of all the values inPayYear2022

(a) (i) Write program code to declare the class Employee . 5 marks

You only need to declare the class and its constructor. Do not declare any other methods.

Use your programming language appropriate constructor.

If you are writing program code in Python, include attribute declarations using comments.

Save your program as Question3_J2023 .

Copy and paste the program code into part 3(a)(i) in the evidence document.

(ii) The method GetEmployeeNumber() returns the employee number. 2 marks

Write program code for the method GetEmployeeNumber() .

Save your program.

Copy and paste the program code into part 3(a)(ii) in the evidence document.

(iii) The method SetPay() : 3 marks

  • takes a week number and the number of hours worked that week as parameters

  • calculates the pay for that week by multiplying the hourly pay by the number of hours worked that week

  • stores the calculated pay in the appropriate index for that week in PayYear2022 .

Write program code for the method SetPay() .

Save your program.

Copy and paste the program code into part 3(a)(iii) in the evidence document.

(iv) The method GetTotalPay() returns the total of all the values in PayYear2022 . 2 marks

Write program code for the method GetTotalPay() .

Save your program.

Copy and paste the program code into part 3(a)(iv) in the evidence document.

(b) The child class Manager inherits from the parent class Employee .

A manager gets a bonus. This bonus value is a percentage, for example 10.0%.

When calculating the pay, the number of hours the manager worked that week is incre by the bonus value. Manager
Manager Manager
BonusValue : REAL stores the bonus value, for example 10.0 represents a
10.0% increase
Constructor()
SetPay()
takes bonus value, hourly pay, employee number and job title
as parameters
initialisesBonusValue to its parameter value
takes the week number and number of hours worked as
parameters
increases the number of hours worked by the bonus value
calls theSetPay() method from the parent class

(i) Write program code to declare the class Manager . 4 marks

You only need to declare the class and its constructor. Do not declare any other methods.

Use your programming language appropriate constructor.

If you are writing in Python, include attribute declarations using comments.

Save your program.

Copy and paste the program code into part 3(b)(i) in the evidence document.

(ii) The Manager method SetPay() overrides the method from the parent class and: 3 marks

  • takes the week number and number of hours worked as parameters

  • increases the number of hours worked by the bonus value

  • calls SetPay() from the parent class.

Write program code for the method SetPay() .

Save your program.

Copy and paste the program code into part 3(b)(ii) in the evidence document.

(c) The main program has a global 1D array, EmployeeArray, to store data about eight employees. Each employee is stored as an object of type Employee . 7 marks

The file Employees.txt stores data about the employees, in the order:

  • hourly pay

  • employee number

  • bonus value (where included)

  • job title.

Only employees who are managers have a bonus value saved. For example:

  • The first employee is a Junior Developer, with employee number 12452 and an hourly pay of $15.22. This employee does not have a bonus value.

  • The third employee is an Interface Manager, with employee number 02586 and an hourly pay of $22.50. This employee has a bonus value of 5.25%.

Write the main program to:

  • declare the array to store data about 8 employees

  • read in the data from the file for each employee

  • instantiate each employee as either Employee (if the employee does not have a bonus value) or Manager (if the employee has a bonus value).

Save your program.

Copy and paste the program code into part 3(c) in the evidence document.

(d) The file HoursWeek1.txt stores the number of hours each employee has worked in week 1, in the order: 4 marks

  • employee number

  • number of hours worked.

For example, the first set of data is for employee 21548 who has worked 50.0 hours.

The procedure EnterHours() :

  • reads in the values from the file

  • finds the location of each employee in EmployeeArray

  • calls the method SetPay() for each employee.

Write program code for EnterHours() .

Save your program.

Copy and paste the program code into part 3(d) in the evidence document. (e) (i) The main program needs to call EnterHours() and use the method GetTotalPay() 2 marks to output the employee number and total pay for each of the eight employees.

Amend the main program to perform these tasks.

Save your program.

Copy and paste the program code into part 3(e)(i) in the evidence document.

(ii) Test your program. 1 mark

Take a screenshot of the output.

Save your program.

Copy and paste the screenshot into part 3(e)(ii) in the evidence document.

A company needs a computer program to store data about its employees. Part of the program is being written using object‑oriented programming. The class `Employee` stores data about the employees. Each employee has an employee number, |a job title and hourly pay rate. The class will also store the amount they are paid each week over a 52‑week year in a 1D array. Employee|| |---|---| |**`Employee`**|**`Employee`**| |`HourlyPay : REAL`<br>`EmployeeNumber : STRING`<br>`JobTitle : STRING`<br>`PayYear2022 : ARRAY[0:51] OF REAL`|stores the amount each employee gets paid each<br>hour<br>stores the employee’s unique number<br>stores the employee’s job title<br>stores the amount the employee has been paid each<br>week| |`Constructor()`<br>`GetEmployeeNumber()`<br>`SetPay()`<br>`GetTotalPay()`|initialises`HourlyPay`, `EmployeeNumber` and<br>`JobTitle` from the values passed as parameters<br>initialises all 52 elements in`PayYear2022` to`0.0`<br>returns the employee number<br>takes the week number and number of hours worked<br>that week as parameters<br>calculates and stores the pay for that week in<br>`PayYear2022`<br>returns the total of all the values in`PayYear2022`| **(a) (i)** Write program code to declare the class `Employee` . <span class="part-marks">5 marks</span> You only need to declare the class and its constructor. Do **not** declare any other methods. Use your programming language appropriate constructor. If you are writing program code in Python, include attribute declarations using comments. Save your program as **Question3_J2023** . Copy and paste the program code into **part 3(a)(i)** in the evidence document. #### (ii) The method `GetEmployeeNumber()` returns the employee number. <span class="part-marks">2 marks</span> Write program code for the method `GetEmployeeNumber()` . Save your program. Copy and paste the program code into **part 3(a)(ii)** in the evidence document. #### (iii) The method `SetPay()` : <span class="part-marks">3 marks</span> - takes a week number and the number of hours worked that week as parameters - calculates the pay for that week by multiplying the hourly pay by the number of hours worked that week - stores the calculated pay in the appropriate index for that week in `PayYear2022` . Write program code for the method `SetPay()` . Save your program. Copy and paste the program code into **part 3(a)(iii)** in the evidence document. #### (iv) The method `GetTotalPay()` returns the total of all the values in `PayYear2022` . <span class="part-marks">2 marks</span> Write program code for the method `GetTotalPay()` . Save your program. Copy and paste the program code into **part 3(a)(iv)** in the evidence document. ### (b) The child class `Manager` inherits from the parent class `Employee` . A manager gets a bonus. This bonus value is a percentage, for example 10.0%. |When calculating the pay, the number of hours the manager worked that week is incre by the bonus value. Manager|| |---|---| |**`Manager`**|**`Manager`**| |`BonusValue : REAL`|stores the bonus value, for example 10.0 represents a<br>10.0% increase| |`Constructor()`<br>`SetPay()`|takes bonus value, hourly pay, employee number and job title<br>as parameters<br>initialises`BonusValue` to its parameter value<br>takes the week number and number of hours worked as<br>parameters<br>increases the number of hours worked by the bonus value<br>calls the`SetPay()` method from the parent class| #### (i) Write program code to declare the class `Manager` . <span class="part-marks">4 marks</span> You only need to declare the class and its constructor. Do **not** declare any other methods. Use your programming language appropriate constructor. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into **part 3(b)(i)** in the evidence document. #### (ii) The `Manager` method `SetPay()` overrides the method from the parent class and: <span class="part-marks">3 marks</span> - takes the week number and number of hours worked as parameters - increases the number of hours worked by the bonus value - calls `SetPay()` from the parent class. Write program code for the method `SetPay()` . Save your program. Copy and paste the program code into **part 3(b)(ii)** in the evidence document. ### (c) The main program has a global 1D array, `EmployeeArray`, to store data about eight employees. Each employee is stored as an object of type `Employee` . <span class="part-marks">7 marks</span> The file `Employees.txt` stores data about the employees, in the order: - hourly pay - employee number - bonus value (where included) - job title. Only employees who are managers have a bonus value saved. For example: - The first employee is a Junior Developer, with employee number 12452 and an hourly pay of $15.22. This employee does not have a bonus value. - The third employee is an Interface Manager, with employee number 02586 and an hourly pay of $22.50. This employee has a bonus value of 5.25%. Write the main program to: - declare the array to store data about 8 employees - read in the data from the file for each employee - instantiate each employee as either `Employee` (if the employee does not have a bonus value) or `Manager` (if the employee has a bonus value). Save your program. Copy and paste the program code into **part 3(c)** in the evidence document. ### (d) The file `HoursWeek1.txt` stores the number of hours each employee has worked in week 1, in the order: <span class="part-marks">4 marks</span> - employee number - number of hours worked. For example, the first set of data is for employee 21548 who has worked 50.0 hours. The procedure `EnterHours()` : - reads in the values from the file - finds the location of each employee in `EmployeeArray` - calls the method `SetPay()` for each employee. Write program code for `EnterHours()` . Save your program. Copy and paste the program code into **part 3(d)** in the evidence document. **(e) (i)** The main program needs to call `EnterHours()` and use the method `GetTotalPay()` <span class="part-marks">2 marks</span> to output the employee number and total pay for each of the eight employees. Amend the main program to perform these tasks. Save your program. Copy and paste the program code into **part 3(e)(i)** in the evidence document. #### (ii) Test your program. <span class="part-marks">1 mark</span> Take a screenshot of the output. Save your program. Copy and paste the screenshot into **part 3(e)(ii)** in the evidence document.
Show mark scheme

3(a)(i)

For X = 0 To 51 PayYear2022(X) = 0.00 Next End Sub End Class Python class Employee: #self.__HourlyPay single #self.__EmployeeNumber string #self.__JobTitle string def init(self, EmpNumP, PayP, JobP): self.__HourlyPay = PayP self.__EmployeeNumber = EmpNumP self.__JobTitle = JobP self.__PayYear2022 = []#array 52 elements single for x in range(0, 52): self.__PayYear2022.append(0.00)

3(a)(ii) [2 marks]

1 mark each Get method header (and end) with no parameters … … returning employee number (without overriding) Example program code: public String GetEmployeeNumber(){ return EmployeeNumber; VB.NET Public Function GetEmployeeNumber() Return EmployeeNumber End Function Python def GetEmployeeNumber(self): return self.__EmployeeNumber

3(a)(iii) [3 marks]

1 mark each Method header (and close) with two parameters (week number and number of hours) Calculates pay as number of hours (parameter) * HourlyPay (attribute) … stores result in correct index in PayYear2022 Example program code: public void SetPay(Integer WeekNumber, Double Hours){ PayYear2022[WeekNumber - 1] = Hours * HourlyPay; VB.NET Overridable Sub SetPay(WeekNumber, Hours) PayYear2022(WeekNumber - 1) = Hours * HourlyPay End Sub Python def SetPay(self, WeekNumber, Hours): self.__PayYear2022[WeekNumber-1] = Hours * self.__HourlyPay

3(a)(iv) [2 marks]

1 mark each Method header (and close) and returning calculated total (ignore parameters, allow return of any reasonable attempt at calculation) Totalling all elements in PayYear2022 Example program code: public Double GetTotalPay(){ Double TotalPay = 0.0; for(Integer X = 0; X < 52; X++){ TotalPay = TotalPay + PayYear2022[X]; } return TotalPay; VB.NET Public Function GetTotalPay() Dim TotalPay As Single = 0 For X = 0 To 51 TotalPay = TotalPay + PayYear2022(X) Next Return TotalPay End Function Python def GetTotalPay(self): TotalPay = 0 for X in range (0, 52): TotalPay = TotalPay + self.__PayYear2022[X] return TotalPay

3(b)(i)

Python class Manager(Employee): #BonusValue single def init(self, EmpNumP, PayP, JobP, BonusP): super().init(EmpNumP, PayP, JobP) self.__BonusValue = BonusP

3(b)(ii) [3 marks]

1 mark each Method SetPay header (and end) taking 2 parameters Calculating hours (from parameter) * bonus as a percentage Overriding / calling parent SetPay with week number from parameter and updated hours as parameters Example program code: public void SetPay(Integer WeekNumber, Double Hours){ super.SetPay(WeekNumber, Hours * ((BonusValue / 100) + 1)); VB.NET Overrides Sub SetPay(WeekNumber, Hours) MyBase.SetPay(WeekNumber, Hours * ((BonusValue / 100) + 1)) End Sub Alternative VB.NET: Overloads Sub SetPay(WeekNumber, Hours) SetPay(WeekNumber, Hours * ((BonusValue / 100) + 1)) End Sub Python def SetPay(self, WeekNumber, Hours): Hours = Hours * (1 + self.__BonusValue / 100) super().SetPay(WeekNumber, Hours)

3(c)

File.close() except IOError: print("Could not find file")

3(d)

VB.NET Sub EnterHours() try Dim TextFile As String = "HoursWeek1.txt" Dim FileReader As New System.IO.StreamReader(TextFile) Dim EmpId As String For X = 0 To 7 EmpId = FileReader.ReadLine() For Y = 0 To 7 If Employees(Y).GetEmployeeNumber = EmpId Then Employees(Y).SetPay(1, CSng(FileReader.ReadLine())) End If Next Next FileReader.Close() Catch ex As Exception Console.WriteLine("Invalid file") End Try End Sub Python def EnterHours(): try: TextFile = "HoursWeek1.txt" File = open(TextFile, 'r') EmpID = "" for X in range(0, 8): EmpID = File.readline() for Y in range(0, 8): if Employees[Y].GetEmployeeNumber() == EmpID: Employees[Y].SetPay(1, float(File.readline())) except IOError: print("Could not find file")

3(e)(i) [2 marks]

1 mark each Calling EnterHours() and looping through each employee … … outputting the employee number and their total pay using GetTotalPay() and GetEmployeeNumber() Example program code: EnterHours(); for(Integer X = 0; X < 8; X++){ System.out.println(Employees[Y].GetEmployeeNumber() + " " + Employees[Y].GetTotalPay()); VB.NET EnterHours() For Y = 0 To 7 Console.WriteLine(Employees(Y).GetEmployeeNumber & " " & Employees(Y).GetTotalPay()) Python EnterHours() for(Y in range(0, 8): print(Employees[Y].GetEmployeeNumber(), " ", Employees[Y].GetTotalPay())

3(e)(ii) [1 mark]

1 mark for screenshot e.g.

Q2
May/Jun 2023 Paper 4 v3

A computer game is being designed that will include different vehicles. A prototype for the game is being developed using object‑oriented programming.

The class Vehicle stores data about the vehicles. Each vehicle has an identification name, a maximum speed, a current speed and a horizontal position. The value IncreaseAmount is added to the current speed each time the vehicle increases its speed.

Vehicle
ID : STRING
MaxSpeed : INTEGER
CurrentSpeed : INTEGER
IncreaseAmount : INTEGER
HorizontalPosition : INTEGER
stores the identification name for the vehicle
stores the maximum speed
stores the current speed
stores the amountCurrentSpeed increases by
stores the horizontal position
Constructor()
GetCurrentSpeed()
GetIncreaseAmount()
GetHorizontalPosition()
GetMaxSpeed()
SetCurrentSpeed()
SetHorizontalPosition()
IncreaseSpeed()
initialisesID, MaxSpeed andIncreaseAmount to the
parameter values
initialises bothCurrentSpeed and
HorizontalPosition to0
returns the current speed
returns the increase amount
returns the horizontal position
returns the maximum speed
assigns the parameter to the current speed
assigns the parameter to the horizontal position
calculates and stores the new speed and horizontal
position of the vehicle

(a) (i) Write program code to declare the class Vehicle . All attributes must be private. 5 marks

You only need to declare the class and its constructor. Do not declare any other methods.

Use your programming language’s appropriate constructor.

If you are writing program code in Python, include attribute declarations using comments.

Save your program as Question2_J2023 .

Copy and paste the program code into part 2(a)(i) in the evidence document.

(ii) Write program code for the get methods GetCurrentSpeed(), GetIncreaseAmount(), GetMaxSpeed() and GetHorizontalPosition() Save your program. 3 marks

Copy and paste the program code into part 2(a)(ii) in the evidence document.

(iii) Write program code for the set methods SetCurrentSpeed() and 3 marks

      SetHorizontalPosition()

Save your program.

Copy and paste the program code into part 2(a)(iii) in the evidence document.

(iv) The method IncreaseSpeed() : 3 marks

  • adds IncreaseAmount to the current speed

  • adds the updated current speed to the horizontal position.

The current speed of a vehicle cannot exceed its maximum speed.

Write program code for the method IncreaseSpeed()

Save your program.

Copy and paste the program code into part 2(a)(iv) in the evidence document.

(b) The child class Helicopter inherits from the parent class Vehicle. A helicopter also has a vertical position and changes the vertical position when it increases speed. Helicopter
Helicopter Helicopter
VerticalPosition : INTEGER
VerticalChange : INTEGER
MaxHeight : INTEGER
stores the vertical position
stores the amountVerticalPosition changes by
stores the maximum height the helicopter can reach
Constructor()
GetVerticalPosition()
IncreaseSpeed()
takes the ID, maximum speed, increase amount, vertical
change and maximum height as parameters
initialises the vertical position to 0
returns the vertical position
changes the current speed, horizontal and vertical
position of the helicopter

(i) Write program code to declare the class Helicopter . You only need to declare the class and its constructor. You do not need to declare the other methods. 5 marks

Use your programming language’s appropriate constructor.

All attributes must be private.

If you are writing in Python, include attribute declarations using comments.

Save your program.

Copy and paste the program code into part 2(b)(i) in the evidence document.

(ii) The Helicopter method IncreaseSpeed() overrides the method from the parent class and: 4 marks

  • adds the amount of vertical change to the vertical position

  • adds IncreaseAmount to the current speed

  • adds the updated current speed to the horizontal position.

The vertical position of a helicopter cannot exceed its maximum height.

The current speed of a helicopter cannot exceed its maximum speed.

Write program code for the method IncreaseSpeed()

Save your program.

Copy and paste the program code into part 2(b)(ii) in the evidence document.

(c) A procedure needs to output the horizontal position and speed of a vehicle. If the vehicle is a helicopter, it also outputs the vertical position. 3 marks

All outputs must include appropriate messages.

Write program code for this procedure.

Save your program.

Copy and paste the program code into part 2(c) in the evidence document.

(d) The main program needs to:

  • instantiate a car as a new vehicle with the ID "Tiger", a maximum speed of 100 and an increase amount of 20

  • instantiate a new helicopter with the ID "Lion", a maximum speed of 350, an increase amount of 40, a vertical change of 3 and a maximum height of 100

  • call IncreaseSpeed() twice for the car and then call the output procedure from part 2(c) for the car

  • call IncreaseSpeed() twice for the helicopter and then call the output procedure from part 2(c) for the helicopter.

(i) Write program code for the main program. 5 marks

Save your program.

Copy and paste the program code into part 2(d)(i) in the evidence document.

(ii) Test your program. 1 mark

Take a screenshot of the output.

Save your program.

Copy and paste the screenshot into part 2(d)(ii) in the evidence document.

A computer game is being designed that will include different vehicles. A prototype for the game is being developed using object‑oriented programming. The class `Vehicle` stores data about the vehicles. Each vehicle has an identification name, a maximum speed, a current speed and a horizontal position. The value `IncreaseAmount` is added to the current speed each time the vehicle increases its speed. |Vehicle|| |---|---| |`ID : STRING`<br>`MaxSpeed : INTEGER`<br>`CurrentSpeed : INTEGER`<br>`IncreaseAmount : INTEGER`<br>`HorizontalPosition : INTEGER`|stores the identification name for the vehicle<br>stores the maximum speed<br>stores the current speed<br>stores the amount`CurrentSpeed` increases by<br>stores the horizontal position| |`Constructor()`<br>`GetCurrentSpeed()`<br>`GetIncreaseAmount()`<br>`GetHorizontalPosition()`<br>`GetMaxSpeed()`<br>`SetCurrentSpeed()`<br>`SetHorizontalPosition()`<br>`IncreaseSpeed()`|initialises`ID`, `MaxSpeed` and`IncreaseAmount` to the<br>parameter values<br>initialises both`CurrentSpeed` and<br>`HorizontalPosition` to`0`<br>returns the current speed<br>returns the increase amount<br>returns the horizontal position<br>returns the maximum speed<br>assigns the parameter to the current speed<br>assigns the parameter to the horizontal position<br>calculates and stores the new speed and horizontal<br>position of the vehicle| **(a) (i)** Write program code to declare the class `Vehicle` . All attributes must be private. <span class="part-marks">5 marks</span> You only need to declare the class and its constructor. Do not declare any other methods. Use your programming language’s appropriate constructor. If you are writing program code in Python, include attribute declarations using comments. Save your program as **Question2_J2023** . Copy and paste the program code into **part 2(a)(i)** in the evidence document. #### (ii) Write program code for the get methods `GetCurrentSpeed()`, `GetIncreaseAmount()`, `GetMaxSpeed()` and `GetHorizontalPosition()` Save your program. <span class="part-marks">3 marks</span> Copy and paste the program code into **part 2(a)(ii)** in the evidence document. #### (iii) Write program code for the set methods `SetCurrentSpeed()` and <span class="part-marks">3 marks</span> ``` SetHorizontalPosition() ``` Save your program. Copy and paste the program code into **part 2(a)(iii)** in the evidence document. #### (iv) The method `IncreaseSpeed()` : <span class="part-marks">3 marks</span> - adds `IncreaseAmount` to the current speed - adds the updated current speed to the horizontal position. The current speed of a vehicle cannot exceed its maximum speed. Write program code for the method `IncreaseSpeed()` Save your program. Copy and paste the program code into **part 2(a)(iv)** in the evidence document. |(b) The child class Helicopter inherits from the parent class Vehicle. A helicopter also has a vertical position and changes the vertical position when it increases speed. Helicopter|| |---|---| |**`Helicopter`**|**`Helicopter`**| |`VerticalPosition : INTEGER`<br>`VerticalChange : INTEGER`<br>`MaxHeight : INTEGER`|stores the vertical position<br>stores the amount`VerticalPosition` changes by<br>stores the maximum height the helicopter can reach| |`Constructor()`<br>`GetVerticalPosition()`<br>`IncreaseSpeed()`|takes the ID, maximum speed, increase amount, vertical<br>change and maximum height as parameters<br>initialises the vertical position to 0<br>returns the vertical position<br>changes the current speed, horizontal and vertical<br>position of the helicopter| #### (i) Write program code to declare the class `Helicopter` . You only need to declare the class and its constructor. You do not need to declare the other methods. <span class="part-marks">5 marks</span> Use your programming language’s appropriate constructor. All attributes must be private. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into **part 2(b)(i)** in the evidence document. #### (ii) The `Helicopter` method `IncreaseSpeed()` overrides the method from the parent class and: <span class="part-marks">4 marks</span> - adds the amount of vertical change to the vertical position - adds `IncreaseAmount` to the current speed - adds the updated current speed to the horizontal position. The vertical position of a helicopter cannot exceed its maximum height. The current speed of a helicopter cannot exceed its maximum speed. Write program code for the method `IncreaseSpeed()` Save your program. Copy and paste the program code into **part 2(b)(ii)** in the evidence document. ### (c) A procedure needs to output the horizontal position and speed of a vehicle. If the vehicle is a helicopter, it also outputs the vertical position. <span class="part-marks">3 marks</span> All outputs must include appropriate messages. Write program code for this procedure. Save your program. Copy and paste the program code into **part 2(c)** in the evidence document. ### (d) The main program needs to: - instantiate a car as a new vehicle with the ID "Tiger", a maximum speed of 100 and an increase amount of 20 - instantiate a new helicopter with the ID "Lion", a maximum speed of 350, an increase amount of 40, a vertical change of 3 and a maximum height of 100 - call `IncreaseSpeed()` twice for the car and then call the output procedure from **part 2(c)** for the car - call `IncreaseSpeed()` twice for the helicopter and then call the output procedure from **part 2(c)** for the helicopter. #### (i) Write program code for the main program. <span class="part-marks">5 marks</span> Save your program. Copy and paste the program code into **part 2(d)(i)** in the evidence document. #### (ii) Test your program. <span class="part-marks">1 mark</span> Take a screenshot of the output. Save your program. Copy and paste the screenshot into **part 2(d)(ii)** in the evidence document.
Show mark scheme

2(a)(i)

public Vehicle(String IDP, Integer MaxSpeedP, Integer IncreaseAmountP){ ID = IDP; MaxSpeed = MaxSpeedP; IncreaseAmount = IncreaseAmountP; CurrentSpeed = 0; HorizontalPosition = 0; }} Python class Vehicle: #self.__ID string #self.__MaxSpeed integer #self.__CurrentSpeed integer #self.__IncreaseAmount integer #self.__HorizontalPosition def init(self, IDP, MaxSpeedP, IncreaseAmountP): self.__ID = IDP self.__MaxSpeed = MaxSpeedP self.__IncreaseAmount = IncreaseAmountP self.__CurrentSpeed = 0 self.__HorizontalPosition = 0

2(a)(ii)

Python def GetCurrentSpeed(self): return self.__CurrentSpeed def GetIncreaseAmount(self): return self.__IncreaseAmount def GetHorizontalPosition(self): return self.__HorizontalPosition def GetMaxSpeed(self): return self.__MaxSpeed

2(a)(iii) [3 marks]

1 mark each 1 set procedure (and end where appropriate) taking parameter … … assigns parameter to the attribute (without overriding) Second correct set method Example program code: VB.NET Sub SetCurrentSpeed(CSp) CurrentSpeed = CSp End Sub Sub SetHorizontalPosition(HPP) HorizontalPosition = HPP End Sub public void SetCurrentSpeed(Integer CSP){ CurrentSpeed = CSP; public void SetHorizontalPosition(Integer HPP){ HorizontalPosition = HPP; Python def SetCurrentSpeed(self, CSP): self.__CurrentSpeed = CSP def SetHorizontalPosition(self, HPP): self.__HorizontalPosition = HPP

2(a)(iv) [3 marks]

1 mark each Method header (and close where appropriate) with no parameter and adding IncreaseAmount to CurrentSpeed Checking if MaxSpeed is exceeded and limiting to max speed (remove increase or assign maximum) Adding updated CurrentSpeed to HorizontalPosition in all cases (whether MaxSpeed is exceeded or not) Example program code: VB.NET Sub IncreaseSpeed() CurrentSpeed = CurrentSpeed + IncreaseAmount If CurrentSpeed > MaxSpeed Then CurrentSpeed = MaxSpeed End If HorizontalPosition = HorizontalPosition + CurrentSpeed End Sub public void IncreaseSpeed(){ CurrentSpeed = CurrentSpeed + IncreaseAmount; if(CurrentSpeed > MaxSpeed){ CurrentSpeed = MaxSpeed; } HorizontalPosition = HorizontalPosition + CurrentSpeed; Python def IncreaseSpeed(self): self.__CurrentSpeed = self.__CurrentSpeed + self.__IncreaseAmount if(self.__CurrentSpeed > self.__MaxSpeed): self.__CurrentSpeed = self.__MaxSpeed self.__HorizontalPosition = self.__HorizontalPosition + self.__CurrentSpeed

2(b)(i)

super(IDP, MaxSpeedP, IncreaseAmountP); VerticalPosition = 0; VerticalChange = VertChangeP; MaxHeight = MaxHeightP; }} Python class Helicopter(Vehicle): #VerticalPosition Integer #VerticalChange Integer #MaxHeight Integer def init(self, IDP, MaxSpeedP, IncreaseAmountP, VertChangeP, MaxHeightP): Vehicle.init(self,IDP, MaxSpeedP, IncreaseAmountP) self.__VerticalPosition = 0 self.__VerticalChange = VertChangeP self.__MaxHeight = MaxHeightP

2(b)(ii)

Python def IncreaseSpeed(self): self.__VerticalPosition = self.__VerticalPosition + self.__VerticalChange if(self.__VerticalPosition > self.__MaxHeight): self.__VerticalPosition = MaxHeight Vehicle.SetCurrentSpeed(self, Vehicle.GetCurrentSpeed(self) + Vehicle.GetIncreaseAmount(self)) if(Vehicle.GetCurrentSpeed(self) > Vehicle.GetMaxSpeed(self)): Vehicle.SetCurrentSpeed(self, Vehicle.GetMaxSpeed(self)); Vehicle.SetHorizontalPosition(self, Vehicle.GetHorizontalPosition(self) + Vehicle.GetCurrentSpeed(self))

2(c)

def OutputCurrentPosition(self): print("Current position = ", Vehicle.GetHorizontalPosition(self)) print("Current speed = ", Vehicle.GetCurrentSpeed(self)) print("Current verticalposition = ", self.__VerticalPosition)

2(d)(i)

Python #main Car = Vehicle("Tiger", 100, 20) Heli1 = Helicopter("Lion", 350, 40, 3, 100) Car.IncreaseSpeed() Car.IncreaseSpeed() Car.OutputCurrentPosition() print("") Heli1.IncreaseSpeed() Heli1.IncreaseSpeed() Heli1.OutputCurrentPosition()

2(d)(ii) [1 mark]

Screenshot of results e.g.

Q7
Oct/Nov 2022 Paper 3 v1

(a) Complete the Karnaugh map (K-map) for the Boolean expression. 2 marks

Z = ¯A. B. ¯C. ¯D + ¯A. B. ¯C. D + A. B. ¯C. ¯D + A. B. ¯C. D + A. ¯B. ¯C. ¯D + A. ¯B. ¯C. D

AB
00 01 11 10
D
00
01
11
10
00
00
01
11
10
AB
D
01
11
10
00
00
01
11
10
AB
D
01
11
10
00
00
01
11
10
AB
D
01
11
10
00
00
01
11
10
AB
D
01
11
10

(b) Draw loop(s) around appropriate group(s) in the K-map to produce an optimal sum-of-products. [2]

(c) Write the Boolean expression from your answer to part (b) as a simplified sum-of-products. 3 marks

Use Boolean algebra to give your answer in its simplest form.

Simplified sum-of-products

Z =

Simplest form

Z =

### (a) Complete the Karnaugh map (K-map) for the Boolean expression. <span class="part-marks">2 marks</span> **Z = ¯A. B. ¯C. ¯D + ¯A. B. ¯C. D + A. B. ¯C. ¯D + A. B. ¯C. D + A. ¯B. ¯C. ¯D + A. ¯B. ¯C. D** |AB<br>00 01 11 10<br>D<br>00<br>01<br>11<br>10||||| |---|---|---|---|---| |**00**<br>**00**<br>**01**<br>**11**<br>**10**<br>**AB**<br>**D**<br>**01**<br>**11**<br>**10**||||| |**00**<br>**00**<br>**01**<br>**11**<br>**10**<br>**AB**<br>**D**<br>**01**<br>**11**<br>**10**||||| |**00**<br>**00**<br>**01**<br>**11**<br>**10**<br>**AB**<br>**D**<br>**01**<br>**11**<br>**10**||||| |**00**<br>**00**<br>**01**<br>**11**<br>**10**<br>**AB**<br>**D**<br>**01**<br>**11**<br>**10**||||| ### (b) Draw loop(s) around appropriate group(s) in the K-map to produce an optimal sum-of-products. [2] ### (c) Write the Boolean expression from your answer to **part (b)** as a simplified sum-of-products. <span class="part-marks">3 marks</span> Use Boolean algebra to give your answer in its simplest form. **Simplified sum-of-products** **Z** = **Simplest form** **Z** =
Show mark scheme

7(a) [2 marks]

Two marks if no errors present One mark if one error present AB 00 01 11 10 CD 00 0 1 1 1 01 0 1 1 1 11 0 0 0 0 10 0 0 0 0

7(b) [2 marks]

One mark for correct loop (Max 2)

7(c) [3 marks]

One mark for each point • Any correct Boolean term • Boolean terms and operator correct and no other terms present _ _ (Z =) BC + AC One mark for simplest form _ (Z =) C (A + B)

Q7
Oct/Nov 2022 Paper 3 v2
Show mark scheme

7 [4 marks]

One mark for each point Supervised learning ( Max 3 of 4 ) • Supervised learning allows data to be collected, or a data output produced, from the previous experience. • In supervised learning, known input and associated outputs are given // uses sample data with known outputs (in training) // uses labelled input data. • Able to predict future outcomes based on past data. Unsupervised learning ( Max 3 of 4) • Unsupervised machine learning helps all kinds of unknown patterns in data to be found. • Unsupervised learning only requires input data to be given. • Uses any data // not trained on the right output // uses unlabelled input data.

Q7
Oct/Nov 2022 Paper 3 v3

(a) Complete the Karnaugh map (K-map) for the Boolean expression. 2 marks

Z = ¯A. B. ¯C. ¯D + ¯A. B. ¯C. D + A. B. ¯C. ¯D + A. B. ¯C. D + A. ¯B. ¯C. ¯D + A. ¯B. ¯C. D

AB
00 01 11 10
D
00
01
11
10
00
00
01
11
10
AB
D
01
11
10
00
00
01
11
10
AB
D
01
11
10
00
00
01
11
10
AB
D
01
11
10
00
00
01
11
10
AB
D
01
11
10

(b) Draw loop(s) around appropriate group(s) in the K-map to produce an optimal sum-of-products. [2]

(c) Write the Boolean expression from your answer to part (b) as a simplified sum-of-products. 3 marks

Use Boolean algebra to give your answer in its simplest form.

Simplified sum-of-products

Z =

Simplest form

Z =

### (a) Complete the Karnaugh map (K-map) for the Boolean expression. <span class="part-marks">2 marks</span> **Z = ¯A. B. ¯C. ¯D + ¯A. B. ¯C. D + A. B. ¯C. ¯D + A. B. ¯C. D + A. ¯B. ¯C. ¯D + A. ¯B. ¯C. D** |AB<br>00 01 11 10<br>D<br>00<br>01<br>11<br>10||||| |---|---|---|---|---| |**00**<br>**00**<br>**01**<br>**11**<br>**10**<br>**AB**<br>**D**<br>**01**<br>**11**<br>**10**||||| |**00**<br>**00**<br>**01**<br>**11**<br>**10**<br>**AB**<br>**D**<br>**01**<br>**11**<br>**10**||||| |**00**<br>**00**<br>**01**<br>**11**<br>**10**<br>**AB**<br>**D**<br>**01**<br>**11**<br>**10**||||| |**00**<br>**00**<br>**01**<br>**11**<br>**10**<br>**AB**<br>**D**<br>**01**<br>**11**<br>**10**||||| ### (b) Draw loop(s) around appropriate group(s) in the K-map to produce an optimal sum-of-products. [2] ### (c) Write the Boolean expression from your answer to **part (b)** as a simplified sum-of-products. <span class="part-marks">3 marks</span> Use Boolean algebra to give your answer in its simplest form. **Simplified sum-of-products** **Z** = **Simplest form** **Z** =
Show mark scheme

7(a) [2 marks]

Two marks if no errors present One mark if one error present AB 00 01 11 10 CD 00 0 1 1 1 01 0 1 1 1 11 0 0 0 0 10 0 0 0 0

7(b) [2 marks]

One mark for correct loop (Max 2)

7(c) [3 marks]

One mark for each point • Any correct Boolean term • Boolean terms and operator correct and no other terms present _ _ (Z =) BC + AC One mark for simplest form _ (Z =) C (A + B)

Q1
Oct/Nov 2022 Paper 4 v1

The text file IntegerData.txt stores 100 integer numbers between 1 and 100 inclusive. A program is required to read in this data and perform searching and sorting on the data.

(a) Write program code to declare a global 1D array, DataArray, with space for 100 integer values. 2 marks

Save your program as Question1_N22 .

Copy and paste the program code into part 1(a) in the evidence document.

(b) The procedure ReadFile() must read in the numbers from the text file and store each one in the array. Use appropriate exception handling. 6 marks

Write program code for the procedure ReadFile() .

Save your program.

Copy and paste the program code into part 1(b) in the evidence document.

(c) The function FindValues() asks the user to enter a number to search for in the array. 7 marks

The number input must be a whole number between 1 and 100 inclusive. The function then returns the number of times the number input appears in the array.

Write program code for the function FindValues() .

Save your program.

Copy and paste the program code into part 1(c) in the evidence document.

The text file `IntegerData.txt` stores 100 integer numbers between 1 and 100 inclusive. A program is required to read in this data and perform searching and sorting on the data. ### (a) Write program code to declare a global 1D array, `DataArray`, with space for 100 integer values. <span class="part-marks">2 marks</span> Save your program as **Question1_N22** . Copy and paste the program code into **part 1(a)** in the evidence document. ### (b) The procedure `ReadFile()` must read in the numbers from the text file and store each one in the array. Use appropriate exception handling. <span class="part-marks">6 marks</span> Write program code for the procedure `ReadFile()` . Save your program. Copy and paste the program code into **part 1(b)** in the evidence document. ### (c) The function `FindValues()` asks the user to enter a number to search for in the array. <span class="part-marks">7 marks</span> The number input must be a whole number between 1 and 100 inclusive. The function then returns the number of times the number input appears in the array. Write program code for the function `FindValues()` . Save your program. Copy and paste the program code into **part 1(c)** in the evidence document.
Show mark scheme

1(a) [2 marks]

1 mark per point: • (global) 1D (Integer) array DataArray • 100 elements Example program code: Python DataArray = [0 for I in range (100)] Java public static Integer[] DataArray = new Integer[100]; VB.NET Dim DataArray(99) As Integer

1(b)

Java public static void ReadFile(){ String Filename = "IntegerData.txt"; try{ FileReader F = new FileReader(Filename); BufferedReader Reader = new BufferedReader(F); for(Integer X = 0; X < 100; X++){ DataArray[X] = Integer.parseInt(Reader.readLine()); } Reader.close(); } catch(FileNotFoundException ex){ System.out.println("No file found"); } catch(IOException ex){ System.out.println("No file found"); } } VB.NET Sub ReadFile() try Dim TextFile As String = "IntegerData.txt" Dim FileReader As New System.IO.StreamReader(TextFile) For X = 0 To 99 DataArray(X) = FileReader.ReadLine() Next FileReader.Close() Catch ex As Exception Console.WriteLine("Invalid file") End Try End Sub

1(c)

Example program code: Python def FindValues(): global DataArray DataToFind = -1 while(DataToFind < 1 or DataToFind > 100): DataToFind = int(input("Enter a number between 1 and 100")) Total = 0 for X in range(0, 99): if DataArray[X] == DataToFind: Total = Total + 1 return Total VB.NET Function FindValues() Dim DataToFind As Integer Do Console.WriteLine("Enter a number between 1 and 100") DataToFind = Console.ReadLine() Loop Until (DataToFind >= 1 And DataToFind <= 100) Dim Total As Integer = 0 For X = 0 To 99 If DataArray(X) = DataToFind Then Total = Total + 1 End If Next Return Total End Function Java public static Integer FindValues(){ Integer DataToFind = -1; while(DataToFind < 1 || DataToFind > 100){ System.out.println("Enter a number between 1 and 100"); Scanner in = new Scanner(System.in); DataToFind = in.nextInt(); } Integer Total = 0; for(Integer X = 0; X < 100; X++){ if(DataArray[X] == DataToFind){ Total = Total + 1; } } return Total; }

1(d)(i) [3 marks]

1 mark per point: • Calling and then (in the main program) ReadFile() FindValues() • storing/using return value from … FindValues() • …outputting return value with appropriate message Example program code: Python ReadFile() print("The number appears " + str(FindValues()) + " times") Java public static void main(String[] args){ ReadFile(); Integer ReturnValue = FindValues(); System.out.println("The number was found " + ReturnValue + " times"); } VB.NET Sub Main() ReadFile() Dim ReturnValue As Integer = FindValues() Console.WriteLine("The number was found " & ReturnValue & " times") End Sub

1(d)(ii) [1 mark]

Screenshot showing 61 input and 2 output, e.g.

1(e)

VB.NET Sub Bubblesort() Dim Outer As Integer = 100 - 1 Dim Swap As Boolean Dim Inner As Integer Dim Temp As Integer Do Inner = 0 Swap = False Do If DataArray(Inner) > DataArray(Inner + 1) Then Temp = DataArray(Inner) DataArray(Inner) = DataArray(Inner + 1) DataArray(Inner + 1) = Temp Swap = True End If Inner = Inner + 1 Loop Until Inner = Outer Outer = Outer - 1 Loop Until Swap = False Or Outer = 0 For X = 0 To 99 Console.WriteLine(DataArray(X)) Next End Sub Sub Main() ReadFile() Dim ReturnValue As Integer = FindValues() Console.WriteLine("The number was found " & ReturnValue & " times") Bubblesort() End Sub

Q1
Oct/Nov 2022 Paper 4 v2

A computer program is needed to store jobs in order of priority. Each job has a job number (for example, 123) and a priority from 1 to 10, with 1 being the highest priority and 10 the lowest.

The program stores the jobs in a global 2D array.

The pseudocode declaration for the array is:

  DECLARE Jobs : ARRAY[0:99, 0:1] OF INTEGER

For example:

  • Jobs[0, 0] stores the job number of the first job.

  • Jobs[0, 1] stores the priority of the first job.

The global variable, NumberOfJobs, stores the number of jobs currently in the array.

(a) Write program code to declare the global 2D array Jobs and the global variable NumberOfJobs . 3 marks

Save your program as Question1_N22 .

Copy and paste the program code into part 1(a) in the evidence document.

(b) The procedure Initialise() stores –1 in each of the array elements and assigns 0 to NumberOfJobs . 3 marks

Write program code for the procedure Initialise() .

Save your program.

Copy and paste the program code into part 1(b) in the evidence document.

A computer program is needed to store jobs in order of priority. Each job has a job number (for example, 123) and a priority from 1 to 10, with 1 being the highest priority and 10 the lowest. The program stores the jobs in a global 2D array. The pseudocode declaration for the array is: ``` DECLARE Jobs : ARRAY[0:99, 0:1] OF INTEGER ``` For example: - `Jobs[0, 0]` stores the job number of the first job. - `Jobs[0, 1]` stores the priority of the first job. The global variable, `NumberOfJobs`, stores the number of jobs currently in the array. ### (a) Write program code to declare the global 2D array `Jobs` and the global variable `NumberOfJobs` . <span class="part-marks">3 marks</span> Save your program as **Question1_N22** . Copy and paste the program code into **part 1(a)** in the evidence document. ### (b) The procedure `Initialise()` stores `–1` in each of the array elements and assigns `0` to `NumberOfJobs` . <span class="part-marks">3 marks</span> Write program code for the procedure `Initialise()` . Save your program. Copy and paste the program code into **part 1(b)** in the evidence document.
Show mark scheme

1(a) [3 marks]

1 mark per point: • (global) 2-D array with correct identifier (and Integer data type) Jobs • … with 100 elements by 2 elements • (global) declared as variable (as Integer) NumberOfJobs Example program code: Java public static Integer[][] Jobs = new Integer[100][2]; public static Integer NumberOfJobs; Python Jobs # global integer, 100 by 2 elements NumberOfJobs # global integer VB.NET Dim Jobs(99, 1) As Integer Dim NumberOfJobs As Integer

1(b) [3 marks]

1 mark per point: • procedure heading (and end where appropriate) and assigns 0 to NumberOfJobs • looping through both array element dimensions • − … assigns 1 to all elements Example program code: Java public static void Initialise(){ for(Integer x = 0; x<100;x++){ for(Integer y = 0; y<2; y++){ Jobs[x][y] = -1; } } NumberOfJobs = 0; } Python def Initialise(): global Jobs global NumberOfJobs for x in range(0, 100): Jobs.append([-1,-1]) NumberOfJobs = 0 VB.NET Sub Initialise() For X = 0 To 99 For Y = 0 To 1 Jobs(X, Y) = -1 Next Next NumberOfJobs = 0 End Sub

1(c) [5 marks]

1 mark per point ( Max 5 ): • Function header (and end where appropriate) with two (integer) parameters • Checks if array is full … • … if full outputs "Not added" • Storing parameters job number and priority to only the next available array position • Incrementing NumberOfJobs • Outputting "Added" if successful Example program code: Java public static void AddJob(Integer Description, Integer Priority){ if(NumberOfJobs == 100){ System.out.println("Not added"); }else{ Jobs[NumberOfJobs][0] = Description; Jobs[NumberOfJobs][1] = Priority; NumberOfJobs = NumberOfJobs + 1; System.out.println("Added"); } } Python def AddJob(JobNumber, Priority): global NumberOfJobs global Jobs if NumberOfJobs == 100: print("Not added") else: Jobs[NumberOfJobs] = [JobNumber, Priority] print("Added") NumberOfJobs = NumberOfJobs + 1 VB.NET Sub AddJob(JobNumber, Priority) If NumberOfJobs = 100 Then Console.WriteLine("Not added") Else Jobs(NumberOfJobs, 0) = JobNumber Jobs(NumberOfJobs, 1) = Priority NumberOfJobs = NumberOfJobs + 1 Console.WriteLine("Added") End If End Sub

1(d) [2 marks]

1 mark per point: • Calls (in the main program) Initialise() • 5 calls with correct values as parameters in correct order AddJob Example program code: Java public static void main(String args[]){ Initialise(); AddJob(12, 10); AddJob(526, 9); AddJob(33,8); AddJob(12,9); AddJob(78,1); } Python Initialise() AddJob(12,10) AddJob(526,9) AddJob(33,8) AddJob(12,9) AddJob(78,1) VB.NET Sub Main() Initialise() AddJob(12, 10) AddJob(526, 9) AddJob(33, 8) AddJob(12, 9) AddJob(78, 1) End Sub

1(e)

VB.NET Sub InsertionSort() Dim Tempa As Integer Dim Tempb As Integer Dim Counter As Integer Dim Placed As Boolean For i = 1 To NumberOfJobs - 1 Tempa = Jobs(i, 0) Tempb = Jobs(i, 1) Counter = i Placed = False While (Counter > 0 And Not Placed) If (Jobs(Counter - 1, 1) > Tempb) Then Jobs(Counter, 0) = Jobs(Counter - 1, 0) Jobs(Counter, 1) = Jobs(Counter - 1, 1) Counter = Counter - 1 Else Placed = True End If End While Jobs(Counter, 0) = Tempa Jobs(Counter, 1) = Tempb Next i End Sub

1(f) [3 marks]

1 mark per point: • procedure heading (and end where appropriate) and outputting all job numbers and priorities • Outputting the job and priority for each element on the same line, with a line break between each job … • … with 'priority' between job number and priority Example program code: Java public static void PrintArray(){ for(Integer x = 0; x < NumberOfJobs; x++){ System.out.println(Jobs[x][0] + " priority " + Jobs[x][1]); } } Python def PrintArray(): global Jobs global NumberOfJobs for X in range(0, NumberOfJobs): print(str(Jobs[X][0]), " priority ", str(Jobs[X][1])) VB.NET Sub PrintArray() For X = 0 To NumberOfJobs - 1 Console.WriteLine(Jobs(X, 0) & " priority " & Jobs(X, 1)) Next End Sub •

1(g)(i) [1 mark]

calling both subroutines in the main program in the correct order Example program code: Java InsertionSort(); PrintArray(); Python InsertionSort() PrintArray() VB.NET InsertionSort() PrintArray()

1(g)(ii) [1 mark]

1 mark for added 5 times and jobs in order. 526 and 12 can be reversed

Q1
Oct/Nov 2022 Paper 4 v3

The text file IntegerData.txt stores 100 integer numbers between 1 and 100 inclusive. A program is required to read in this data and perform searching and sorting on the data.

(a) Write program code to declare a global 1D array, DataArray, with space for 100 integer values. 2 marks

Save your program as Question1_N22 .

Copy and paste the program code into part 1(a) in the evidence document.

(b) The procedure ReadFile() must read in the numbers from the text file and store each one in the array. Use appropriate exception handling. 6 marks

Write program code for the procedure ReadFile() .

Save your program.

Copy and paste the program code into part 1(b) in the evidence document.

(c) The function FindValues() asks the user to enter a number to search for in the array. 7 marks

The number input must be a whole number between 1 and 100 inclusive. The function then returns the number of times the number input appears in the array.

Write program code for the function FindValues() .

Save your program.

Copy and paste the program code into part 1(c) in the evidence document.

The text file `IntegerData.txt` stores 100 integer numbers between 1 and 100 inclusive. A program is required to read in this data and perform searching and sorting on the data. ### (a) Write program code to declare a global 1D array, `DataArray`, with space for 100 integer values. <span class="part-marks">2 marks</span> Save your program as **Question1_N22** . Copy and paste the program code into **part 1(a)** in the evidence document. ### (b) The procedure `ReadFile()` must read in the numbers from the text file and store each one in the array. Use appropriate exception handling. <span class="part-marks">6 marks</span> Write program code for the procedure `ReadFile()` . Save your program. Copy and paste the program code into **part 1(b)** in the evidence document. ### (c) The function `FindValues()` asks the user to enter a number to search for in the array. <span class="part-marks">7 marks</span> The number input must be a whole number between 1 and 100 inclusive. The function then returns the number of times the number input appears in the array. Write program code for the function `FindValues()` . Save your program. Copy and paste the program code into **part 1(c)** in the evidence document.
Show mark scheme

1(a) [2 marks]

1 mark per point: • (global) 1D (Integer) array DataArray • 100 elements Example program code: Python DataArray = [0 for I in range (100)] Java public static Integer[] DataArray = new Integer[100]; VB.NET Dim DataArray(99) As Integer

1(b)

Java public static void ReadFile(){ String Filename = "IntegerData.txt"; try{ FileReader F = new FileReader(Filename); BufferedReader Reader = new BufferedReader(F); for(Integer X = 0; X < 100; X++){ DataArray[X] = Integer.parseInt(Reader.readLine()); } Reader.close(); } catch(FileNotFoundException ex){ System.out.println("No file found"); } catch(IOException ex){ System.out.println("No file found"); } } VB.NET Sub ReadFile() try Dim TextFile As String = "IntegerData.txt" Dim FileReader As New System.IO.StreamReader(TextFile) For X = 0 To 99 DataArray(X) = FileReader.ReadLine() Next FileReader.Close() Catch ex As Exception Console.WriteLine("Invalid file") End Try End Sub

1(c)

Example program code: Python def FindValues(): global DataArray DataToFind = -1 while(DataToFind < 1 or DataToFind > 100): DataToFind = int(input("Enter a number between 1 and 100")) Total = 0 for X in range(0, 99): if DataArray[X] == DataToFind: Total = Total + 1 return Total VB.NET Function FindValues() Dim DataToFind As Integer Do Console.WriteLine("Enter a number between 1 and 100") DataToFind = Console.ReadLine() Loop Until (DataToFind >= 1 And DataToFind <= 100) Dim Total As Integer = 0 For X = 0 To 99 If DataArray(X) = DataToFind Then Total = Total + 1 End If Next Return Total End Function Java public static Integer FindValues(){ Integer DataToFind = -1; while(DataToFind < 1 || DataToFind > 100){ System.out.println("Enter a number between 1 and 100"); Scanner in = new Scanner(System.in); DataToFind = in.nextInt(); } Integer Total = 0; for(Integer X = 0; X < 100; X++){ if(DataArray[X] == DataToFind){ Total = Total + 1; } } return Total; }

1(d)(i) [3 marks]

1 mark per point: • Calling and then (in the main program) ReadFile() FindValues() • storing/using return value from … FindValues() • …outputting return value with appropriate message Example program code: Python ReadFile() print("The number appears " + str(FindValues()) + " times") Java public static void main(String[] args){ ReadFile(); Integer ReturnValue = FindValues(); System.out.println("The number was found " + ReturnValue + " times"); } VB.NET Sub Main() ReadFile() Dim ReturnValue As Integer = FindValues() Console.WriteLine("The number was found " & ReturnValue & " times") End Sub

1(d)(ii) [1 mark]

Screenshot showing 61 input and 2 output, e.g.

1(e)

VB.NET Sub Bubblesort() Dim Outer As Integer = 100 - 1 Dim Swap As Boolean Dim Inner As Integer Dim Temp As Integer Do Inner = 0 Swap = False Do If DataArray(Inner) > DataArray(Inner + 1) Then Temp = DataArray(Inner) DataArray(Inner) = DataArray(Inner + 1) DataArray(Inner + 1) = Temp Swap = True End If Inner = Inner + 1 Loop Until Inner = Outer Outer = Outer - 1 Loop Until Swap = False Or Outer = 0 For X = 0 To 99 Console.WriteLine(DataArray(X)) Next End Sub Sub Main() ReadFile() Dim ReturnValue As Integer = FindValues() Console.WriteLine("The number was found " & ReturnValue & " times") Bubblesort() End Sub

Q2
May/Jun 2022 Paper 3 v1

A declarative language is used to represent the following facts about cats.

  01 type(leopard, wild).
  02 type(lion, wild).
  03 type(cheetah, wild).
  04 type(savannah, hybrid).
  05 type(persian, domestic).
  06
  07 hair(leopard, medium).
  08 hair(lion, short).
  09 hair(cheetah, medium).
  10 hair(savannah, medium).
  11 hair(persian, long).
  12
  13 spots(leopard, yes).
  14 spots(lion, no).
  15 spots(cheetah, yes).
  16 spots(savannah, yes).
  17 spots(persian, no).

These clauses have the following meaning:

Clause Meaning
01 A leopard is a type of wild cat.
08 A lion has short hair.
16 A savannah has spots.
A declarative language is used to represent the following facts about cats. ``` 01 type(leopard, wild). 02 type(lion, wild). 03 type(cheetah, wild). 04 type(savannah, hybrid). 05 type(persian, domestic). 06 07 hair(leopard, medium). 08 hair(lion, short). 09 hair(cheetah, medium). 10 hair(savannah, medium). 11 hair(persian, long). 12 13 spots(leopard, yes). 14 spots(lion, no). 15 spots(cheetah, yes). 16 spots(savannah, yes). 17 spots(persian, no). ``` These clauses have the following meaning: |Clause|Meaning| |---|---| |`01`|A leopard is a type of wild cat.| |`08`|A lion has short hair.| |`16`|A savannah has spots.|
Show mark scheme

2(a) [2 marks]

type(caracal, wild). hair(caracal, short).

2(b) [1 mark]

persian

2(c)(i) [1 mark]

type(Pet, domestic).

2(c)(ii) [2 marks]

spots(WildSpotty, yes) ,type(WildSpotty, wild).

Q7
May/Jun 2022 Paper 3 v1

A program is to be written using Object-Oriented Programming (OOP) for a shop that sells knitting yarn. There are three types of yarn: acrylic, wool or mix.

The following data are stored for each type.

  • Name

  • Colour

  • Batch code

  • Weight

  • Number of balls of yarn in stock (can be edited)

  • Type of yarn

The following statements apply to yarn.

  • Acrylic can be soft or not soft.

  • Wool can be lamb, merino or alpaca.

  • Mix contains a percentage of acrylic.

Each type of yarn has a method that will display all the information about the yarn.

(a) Complete this class inheritance diagram to show the properties, methods and inheritance . 5 marks

Yarn
Name: STRING
Colour: STRING
BatchCode: STRING
Weight: INTEGER
NumberBalls: INTEGER
Type: STRING
Constructor()
EditNumberBalls()
YarnInfo()
Acrylic Wool Mix
                           Percentage: INTEGER
Constructor()
YarnInfo()
Constructor()
Constructor()

(b) Describe what is meant by the terms properties, methods and inheritance . 6 marks

Properties

Methods

Inheritance

A program is to be written using Object-Oriented Programming (OOP) for a shop that sells knitting yarn. There are three types of yarn: acrylic, wool or mix. The following data are stored for each type. - Name - Colour - Batch code - Weight - Number of balls of yarn in stock (can be edited) - Type of yarn The following statements apply to yarn. - Acrylic can be soft or not soft. - Wool can be lamb, merino or alpaca. - Mix contains a percentage of acrylic. Each type of yarn has a method that will display all the information about the yarn. ### (a) Complete this class inheritance diagram to show the **properties**, **methods** and **inheritance** . <span class="part-marks">5 marks</span> ``` Yarn ``` ``` Name: STRING ``` ``` Colour: STRING ``` ``` BatchCode: STRING ``` ``` Weight: INTEGER ``` ``` NumberBalls: INTEGER ``` ``` Type: STRING ``` ``` Constructor() ``` ``` EditNumberBalls() ``` ``` YarnInfo() ``` ``` Acrylic Wool Mix Percentage: INTEGER ``` ``` Constructor() YarnInfo() ``` ``` Constructor() ``` ``` Constructor() ``` ### (b) Describe what is meant by the terms **properties**, **methods** and **inheritance** . <span class="part-marks">6 marks</span> Properties Methods Inheritance
Show mark scheme

7(a) [5 marks]

1 mark per point Acrylic has attribute Soft of type BOOLEAN has attribute WoolType with suitable data type Acrylic and Wool have method YarnInfo() Acrylic , Wool and Mix at least one inherit (one arrow correct) from Yarn … Acrylic , Wool and Mix all inherit (all arrows correct) from Yarn Yarn Name: STRING Colour: STRING BatchCode: STRING Weight: INTEGER NumberBalls: INTEGER Type: STRING Constructor() EditNumberBalls() YarnInfo() Mix Percentage: INTEGER Constructor() YarnInfo() Acrylic Soft: BOOLEAN Constructor() YarnInfo() Wool WoolType: STRING Constructor() YarnInfo()

7(b) [6 marks]

Properties max 2 : the data items / attributes the data types // characteristics defined in a class Methods max 2 : the procedures/ functions / programmed instructions in a class / super class / base class … implementing the behaviours … that act on the properties / attributes Inheritance max 2 : Methods and properties / attributes contained in one class/ super class / base class Are made available to / reused by another class/ derived class

Q2
May/Jun 2022 Paper 3 v2

A declarative language is used to represent the following facts about a school.

  01 teaches(alan, mathematics).
  02 teaches(ioana, geography).
  03 teaches(nina, history).
  04 teaches(alan, statistics).
  05
  06 studies(ahmed, history).
  07 studies(freya, history).
  08 studies(kim, history).
  09 studies(freya, geography).
  10 studies(hua, mathematics).
  11 studies(hua, statistics).
  12 studies(hua, geography).
  13
  14 tutors(alan, kim).
  15 tutors(alan, hua).
  16 tutors(alan, freya).
  17 tutors(nina, ahmed).

These clauses have the following meaning:

Clause Meaning
01 Alan teaches mathematics.
06 Ahmed studies history.
14 Alan is Kim’s tutor.

(a) More facts are to be included. Sam studies history and Nina is his tutor. 2 marks

Write the additional clauses to record these facts.

18

19

(b) Using the variable Student, the goal:

      studies(Student, history)

returns

      Student = freya, ahmed, kim

Write the result returned by the goal:

      studies(Student, geography)

Student = [1]

A declarative language is used to represent the following facts about a school. ``` 01 teaches(alan, mathematics). 02 teaches(ioana, geography). 03 teaches(nina, history). 04 teaches(alan, statistics). 05 06 studies(ahmed, history). 07 studies(freya, history). 08 studies(kim, history). 09 studies(freya, geography). 10 studies(hua, mathematics). 11 studies(hua, statistics). 12 studies(hua, geography). 13 14 tutors(alan, kim). 15 tutors(alan, hua). 16 tutors(alan, freya). 17 tutors(nina, ahmed). ``` These clauses have the following meaning: |Clause|Meaning| |---|---| |`01`|Alan teaches mathematics.| |`06`|Ahmed studies history.| |`14`|Alan is Kim’s tutor.| ### (a) More facts are to be included. Sam studies history and Nina is his tutor. <span class="part-marks">2 marks</span> Write the additional clauses to record these facts. `18` `19` ### (b) Using the variable `Student`, the goal: ``` studies(Student, history) ``` returns ``` Student = freya, ahmed, kim ``` Write the result returned by the goal: ``` studies(Student, geography) ``` `Student =` [1]
Show mark scheme

2(a) [2 marks]

studies(sam, history). tutors(nina, sam).

2(b) [1 mark]

freya, hua // hua, freya

2(c) [4 marks]

mark for correct use of X mark for two other variables in correct positions mark for three correct clauses in any order mark for correct syntax teaches(R, S), studies(X, S), tutors(R, X).

Q7
May/Jun 2022 Paper 3 v2

A digital signature is used to validate the authenticity of an electronic message.

In order to produce a digital signature, a digital certificate is required.

(a) State how a digital certificate is obtained. 3 marks

(b) (i) Explain how a digital signature is produced before the message is sent. 3 marks

(ii) Explain how the digital signature can be checked on receipt to ensure that the message has not been altered during transmission. 4 marks

A digital signature is used to validate the authenticity of an electronic message. In order to produce a digital signature, a digital certificate is required. ### (a) State how a digital certificate is obtained. <span class="part-marks">3 marks</span> **(b) (i)** Explain how a digital signature is produced before the message is sent. <span class="part-marks">3 marks</span> #### (ii) Explain how the digital signature can be checked on receipt to ensure that the message has not been altered during transmission. <span class="part-marks">4 marks</span>
Show mark scheme

7(a) [3 marks]

three from enquiry made to Certificate Authority (CA) enquirer’s details checked by CA if enquirer details verified by CA then public key is agreed CA creates/issues certificate that includes the enquirers public key encrypting data sent to/by CA with the CA’s public/private key

7(b)(i) [3 marks]

The message is hashed with (the agreed hashing algorithm)… … to produce a message digest The message digest is then encrypted with the sender’s private key to form the digital signature

7(b)(ii) [4 marks]

four from The message together with the digital signature is decrypted using the receiver’s private key The digital signature received is decrypted with the sender’s public key to recover the message digest sent The decrypted message received is hashed with the agreed hashing algorithm to reproduce the message digest of the message received The two message digests are compared … if they are the same the message has not been altered // if they are different the message has been altered

Q2
May/Jun 2022 Paper 3 v3

A declarative language is used to represent the following facts about cats.

  01 type(leopard, wild).
  02 type(lion, wild).
  03 type(cheetah, wild).
  04 type(savannah, hybrid).
  05 type(persian, domestic).
  06
  07 hair(leopard, medium).
  08 hair(lion, short).
  09 hair(cheetah, medium).
  10 hair(savannah, medium).
  11 hair(persian, long).
  12
  13 spots(leopard, yes).
  14 spots(lion, no).
  15 spots(cheetah, yes).
  16 spots(savannah, yes).
  17 spots(persian, no).

These clauses have the following meaning:

Clause Meaning
01 A leopard is a type of wild cat.
08 A lion has short hair.
16 A savannah has spots.
A declarative language is used to represent the following facts about cats. ``` 01 type(leopard, wild). 02 type(lion, wild). 03 type(cheetah, wild). 04 type(savannah, hybrid). 05 type(persian, domestic). 06 07 hair(leopard, medium). 08 hair(lion, short). 09 hair(cheetah, medium). 10 hair(savannah, medium). 11 hair(persian, long). 12 13 spots(leopard, yes). 14 spots(lion, no). 15 spots(cheetah, yes). 16 spots(savannah, yes). 17 spots(persian, no). ``` These clauses have the following meaning: |Clause|Meaning| |---|---| |`01`|A leopard is a type of wild cat.| |`08`|A lion has short hair.| |`16`|A savannah has spots.|
Show mark scheme

2(a) [2 marks]

type(caracal, wild). hair(caracal, short).

2(b) [1 mark]

persian

2(c)(i) [1 mark]

type(Pet, domestic).

2(c)(ii) [2 marks]

spots(WildSpotty, yes) ,type(WildSpotty, wild).

Q7
May/Jun 2022 Paper 3 v3

A program is to be written using Object-Oriented Programming (OOP) for a shop that sells knitting yarn. There are three types of yarn: acrylic, wool or mix.

The following data are stored for each type.

  • Name

  • Colour

  • Batch code

  • Weight

  • Number of balls of yarn in stock (can be edited)

  • Type of yarn

The following statements apply to yarn.

  • Acrylic can be soft or not soft.

  • Wool can be lamb, merino or alpaca.

  • Mix contains a percentage of acrylic.

Each type of yarn has a method that will display all the information about the yarn.

(a) Complete this class inheritance diagram to show the properties, methods and inheritance . 5 marks

Yarn
Name: STRING
Colour: STRING
BatchCode: STRING
Weight: INTEGER
NumberBalls: INTEGER
Type: STRING
Constructor()
EditNumberBalls()
YarnInfo()
Acrylic Wool Mix
                           Percentage: INTEGER
Constructor()
YarnInfo()
Constructor()
Constructor()

(b) Describe what is meant by the terms properties, methods and inheritance . 6 marks

Properties

Methods

Inheritance

A program is to be written using Object-Oriented Programming (OOP) for a shop that sells knitting yarn. There are three types of yarn: acrylic, wool or mix. The following data are stored for each type. - Name - Colour - Batch code - Weight - Number of balls of yarn in stock (can be edited) - Type of yarn The following statements apply to yarn. - Acrylic can be soft or not soft. - Wool can be lamb, merino or alpaca. - Mix contains a percentage of acrylic. Each type of yarn has a method that will display all the information about the yarn. ### (a) Complete this class inheritance diagram to show the **properties**, **methods** and **inheritance** . <span class="part-marks">5 marks</span> ``` Yarn ``` ``` Name: STRING ``` ``` Colour: STRING ``` ``` BatchCode: STRING ``` ``` Weight: INTEGER ``` ``` NumberBalls: INTEGER ``` ``` Type: STRING ``` ``` Constructor() ``` ``` EditNumberBalls() ``` ``` YarnInfo() ``` ``` Acrylic Wool Mix Percentage: INTEGER ``` ``` Constructor() YarnInfo() ``` ``` Constructor() ``` ``` Constructor() ``` ### (b) Describe what is meant by the terms **properties**, **methods** and **inheritance** . <span class="part-marks">6 marks</span> Properties Methods Inheritance
Show mark scheme

7(a) [5 marks]

1 mark per point Acrylic has attribute Soft of type BOOLEAN has attribute WoolType with suitable data type Acrylic and Wool have method YarnInfo() Acrylic , Wool and Mix at least one inherit (one arrow correct) from Yarn … Acrylic , Wool and Mix all inherit (all arrows correct) from Yarn Yarn Name: STRING Colour: STRING BatchCode: STRING Weight: INTEGER NumberBalls: INTEGER Type: STRING Constructor() EditNumberBalls() YarnInfo() Mix Percentage: INTEGER Constructor() YarnInfo() Acrylic Soft: BOOLEAN Constructor() YarnInfo() Wool WoolType: STRING Constructor() YarnInfo()

7(b) [6 marks]

Properties max 2 : the data items / attributes the data types // characteristics defined in a class Methods max 2 : the procedures/ functions / programmed instructions in a class / super class / base class … implementing the behaviours … that act on the properties / attributes Inheritance max 2 : Methods and properties / attributes contained in one class/ super class / base class Are made available to / reused by another class/ derived class

Q1
May/Jun 2022 Paper 4 v1

The text file HighScore.txt stores the players who have scored the top ten scores in a game, in descending order of score. The file stores the 3-character name of the player, and their integer score, in the order: player, score.

For example, the current top player in the text file:

FYI is the player name

10 000 is the score

The program:

  • reads in the data from HighScore.txt

  • allows the user to enter a new player name and their score

  • if appropriate, inserts the new player (name and score) into the top ten

  • writes the top ten players (name and score) into a new text file NewHighScore.txt

(a) The program stores the players and their scores in an array of 11 elements (10 elements to be read from the file, 1 element to be inserted by the user). 2 marks

Write a program to declare one or more arrays, as global data structures, to store the player names and their scores.

Save your program as Question1_J2022 .

Copy and paste the program code into part 1(a) in the evidence document.

(b) The procedure ReadHighScores() opens the file HighScore.txt and reads the data into the data structure(s) declared in part 1(a) . 6 marks

Write program code to declare the procedure ReadHighScores() .

Save your program.

Copy and paste the program code into part 1(b) in the evidence document.

The text file `HighScore.txt` stores the players who have scored the top ten scores in a game, in descending order of score. The file stores the 3-character name of the player, and their integer score, in the order: player, score. For example, the current top player in the text file: `FYI` is the player name `10 000` is the score The program: - reads in the data from `HighScore.txt` - allows the user to enter a new player name and their score - if appropriate, inserts the new player (name and score) into the top ten - writes the top ten players (name and score) into a new text file `NewHighScore.txt` ### (a) The program stores the players and their scores in an array of 11 elements (10 elements to be read from the file, 1 element to be inserted by the user). <span class="part-marks">2 marks</span> Write a program to declare one or more arrays, as global data structures, to store the player names and their scores. Save your program as **Question1_J2022** . Copy and paste the program code into **part 1(a)** in the evidence document. ### (b) The procedure `ReadHighScores()` opens the file `HighScore.txt` and reads the data into the data structure(s) declared in **part 1(a)** . <span class="part-marks">6 marks</span> Write program code to declare the procedure `ReadHighScores()` . Save your program. Copy and paste the program code into **part 1(b)** in the evidence document.
Show mark scheme

1(a) [2 marks]

1 mark per mark point declaration of at least 1 array with appropriate identifier … 11 elements (and appropriate data type(s)) Example program code: Public static String[][] FileData = new String[10][2]; VB.NET Dim FileData(0 To 9, 0 To 1) As String Python FileData = [[""] *2 for i in range(11)] #string

1(b)

Python def ReadHighScores(): Filename = "HighScore.txt" File = open(Filename, 'r') for x in range(0, 10): FileData[x][0] = File.readline()[:3] FileData[x][1] = File.readline() File.close VB.NET Sub ReadHighScores() Dim Textfile As String = "HighScore.txt" Dim FileReader As New System.IO.StreamReader(textfile) Dim DataEntered As Integer = 0 While FileReader.Peek <> -1 and DataEntered < 10 FileData(DataEntered, 0) = FileReader.ReadLine() FileData(DataEntered, 1) = FileReader.ReadLine() DataEntered = DataEntered + 1 End While FileReader.Close() End Sub

1(c) [3 marks]

1 mark per mark point procedure heading and end looping through all data structure elements outputting player name, space, score. Each player must start on a new line Example program code: public static void OutputHighScores(){ for(Integer x = 0; x < 11; x++){ System.out.println(FileData[x][0] + " " + FileData[x][1]); Python def OutputHighScores (): for x in range(0, 11): Output = FileData[x][0] + " " + FileData[x][1] print(Output) VB.NET Sub OutputHighScores () For x = 0 To 10 Console.WriteLine(FileData(x, 0) & " " & FileData(x,1)) Next End Sub

1(d)(i) [2 marks]

1 mark per mark point (Main program) calls ReadHighScores() … then calls OutputHighScores() Example program code: public static void main(String[] args){ ReadHighScores(); OutputHighScores(); Python ReadHighScores() OutputHighScore() VB.NET Sub Main() ReadHighScores() OutputHighScore() Console.ReadLine() End Sub

1(d)(ii) [1 mark]

1 mark for screenshot showing the 10 names and scores from the file (and one extra blank space may, or may not be included)

1(e)(i)

VB.NET Console.WriteLine("Enter Username") Username = "ABCD" While Username.length <> 3 Username = Console.ReadLine() End While Score = -1 While Score < 1 Or Score > 100000 Console.WriteLine("Enter score") Score = Console.ReadLine() End While

1(e)(ii)

VB.NET Sub Arrange(Username, Score) Dim Temp1 As String Dim Temp2 As String Dim Second1 As String Dim Second2 As String For x = 0 To 9 If Score > Integer.Parse(FileData(x, 1)) Then Temp1 = FileData(x, 0) Temp2 = FileData(x, 1) FileData(x, 0) = Username FileData(x, 1) = Score.ToString For Count = x + 1 To 9 Second1 = FileData(Count, 0) Second2 = FileData(Count, 1) FileData(Count, 0) = Temp1 FileData(Count, 1) = Temp2 Temp1 = Second1 Temp2 = Second2 x = 10 Next End If Next End Sub

1(e)(iii)

VB.NET OutputHighScore() Username = Console.ReadLine() Score = -1 While(score < 0 or Score > 100000) Score = Console.ReadLine() End While Arrange(Username, Score) OutputHighScore()

1(e)(iv) [1 mark]

1 mark for screenshot. JKL, 9999 entered. After shows JKL in the second position.

1(f)

VB.NET Sub WriteTopTen() Dim Filename As String = " NewHighScore.txt" Dim NewFile As New System.IO.StreamWriter(Filename) For x = 0 To 9 NewFile.WriteLine(FileData(x, 0)) NewFile.WriteLine(FileData(x, 1)) Next NewFile.Close() End Sub

Q1
May/Jun 2022 Paper 4 v2

A program needs to use a stack data structure. The stack can store up to 10 integer elements.

A 1D array StackData is used to store the stack globally. The global variable StackPointer points to the next available space in the stack and is initialised to 0.

(a) Write program code to declare the array and pointer as global data structures. Initialise the pointer to 0. 3 marks

Save your program as Question1_J22 .

Copy and paste the program code into part 1(a) in the evidence document.

(b) Write a procedure to output all 10 elements in the stack and the value of StackPointer . 3 marks

Save your program.

Copy and paste the program code into part 1(b) in the evidence document.

(c) The function Push() takes an integer parameter and returns FALSE if the stack is full. If the stack is not full, it puts the parameter value on the stack, updates the relevant pointer and returns TRUE . 6 marks

Write program code for the function Push() .

Save your program.

Copy and paste the program code into part 1(c) in the evidence document.

A program needs to use a stack data structure. The stack can store up to 10 integer elements. A 1D array `StackData` is used to store the stack globally. The global variable `StackPointer` points to the next available space in the stack and is initialised to 0. ### (a) Write program code to declare the array and pointer as global data structures. Initialise the pointer to 0. <span class="part-marks">3 marks</span> Save your program as **Question1_J22** . Copy and paste the program code into **part 1(a)** in the evidence document. ### (b) Write a procedure to output all 10 elements in the stack **and** the value of `StackPointer` . <span class="part-marks">3 marks</span> Save your program. Copy and paste the program code into **part 1(b)** in the evidence document. ### (c) The function `Push()` takes an integer parameter and returns `FALSE` if the stack is full. If the stack is not full, it puts the parameter value on the stack, updates the relevant pointer and returns `TRUE` . <span class="part-marks">6 marks</span> Write program code for the function `Push()` . Save your program. Copy and paste the program code into **part 1(c)** in the evidence document.
Show mark scheme

1(a) [3 marks]

1 mark per mark point declaring array StackData and pointer StackPointer as (global data structures) StackData has 10 integer elements StackPointer initialised to 0 Example program code: VB.NET Dim StackData(9) As Integer Dim StackPointer As Integer Sub Main() StackPointer = 0 end Sub Python global StackData #integer global StackPointer StackData = [0,0,0,0,0,0,0,0,0,0] #integer StackPointer = 0 import java.util.Scanner; public static Integer[] StackData; public static Integer StackPointer; public static void main(String args[]){ StackData = new Integer[10]; StackPointer = 0; }

1(b) [3 marks]

1 mark per mark point procedure header with sensible identifier (and end where appropriate) outputting StackPointer outputting all 10 elements in array Example program code: VB.NET Sub PrintArray() Console.WriteLine(StackPointer) For x = 0 To 9 Console.WriteLine(StackData(x)) Next End Sub Python def PrintArray(): global StackData global StackPointer print(StackPointer) for x in range (0, 10): print(StackData[x]) public static void PrintArray(){ System.out.println(StackPointer); for(int x = 0; x < 10 ;x++){ System.out.println(StackData[x]); }

1(c)

public static Boolean Push(Integer DataToPush){ if(StackPointer == 10){ return false; }else{ StackData[StackPointer] = DataToPush; StackPointer = StackPointer + 1; return true; }

1(d)(i)

Python #main StackPointer = 0 StackData = [0,0,0,0,0,0,0,0,0,0] for x in range(0, 11): TempNumber = int(input("Enter a number")) if Push(TempNumber) == True: print("Stored") else: print("Stack full") PrintArray() public static void main(String[] args){ StackData = new Integer[10]; StackPointer = 0; Integer TempNumber = 0; for(int x = 0; x < 10; x++){ System.out.println("Enter a number"); Scanner scanner = new Scanner(System.in); TempNumber = Integer.parseInt(scanner.nextLine()); if(Push(TempNumber)){ System.out.println("Stored"); }else{ System.out.println("Stack full"); } } PrintArray();

1(d)(ii) [1 mark]

1 mark for inputting all 11 numbers, message for first 10 saying added (11 to 20), message stating 11th number stating stack full. Full array contents output (11 12 13 14 15 16 17 18 19 20).

1(e)(i)

public static Integer Pop(){ Integer ReturnData = 0; if(StackPointer == 0){ return -1; }else{ ReturnData = StackData[StackPointer - 1]; StackPointer = StackPointer - 1; return ReturnData; }

1(e)(ii) [2 marks]

1 mark per mark point output of before removed with 11 inputs output of stack (after, this could be 11–20, 11–18, or 11–18 then ‘null’ ‘null’s)

Q1
May/Jun 2022 Paper 4 v3

The text file HighScore.txt stores the players who have scored the top ten scores in a game, in descending order of score. The file stores the 3-character name of the player, and their integer score, in the order: player, score.

For example, the current top player in the text file:

FYI is the player name

10 000 is the score

The program:

  • reads in the data from HighScore.txt

  • allows the user to enter a new player name and their score

  • if appropriate, inserts the new player (name and score) into the top ten

  • writes the top ten players (name and score) into a new text file NewHighScore.txt

(a) The program stores the players and their scores in an array of 11 elements (10 elements to be read from the file, 1 element to be inserted by the user). 2 marks

Write a program to declare one or more arrays, as global data structures, to store the player names and their scores.

Save your program as Question1_J2022 .

Copy and paste the program code into part 1(a) in the evidence document.

(b) The procedure ReadHighScores() opens the file HighScore.txt and reads the data into the data structure(s) declared in part 1(a) . 6 marks

Write program code to declare the procedure ReadHighScores() .

Save your program.

Copy and paste the program code into part 1(b) in the evidence document.

The text file `HighScore.txt` stores the players who have scored the top ten scores in a game, in descending order of score. The file stores the 3-character name of the player, and their integer score, in the order: player, score. For example, the current top player in the text file: `FYI` is the player name `10 000` is the score The program: - reads in the data from `HighScore.txt` - allows the user to enter a new player name and their score - if appropriate, inserts the new player (name and score) into the top ten - writes the top ten players (name and score) into a new text file `NewHighScore.txt` ### (a) The program stores the players and their scores in an array of 11 elements (10 elements to be read from the file, 1 element to be inserted by the user). <span class="part-marks">2 marks</span> Write a program to declare one or more arrays, as global data structures, to store the player names and their scores. Save your program as **Question1_J2022** . Copy and paste the program code into **part 1(a)** in the evidence document. ### (b) The procedure `ReadHighScores()` opens the file `HighScore.txt` and reads the data into the data structure(s) declared in **part 1(a)** . <span class="part-marks">6 marks</span> Write program code to declare the procedure `ReadHighScores()` . Save your program. Copy and paste the program code into **part 1(b)** in the evidence document.
Show mark scheme

1(a) [2 marks]

1 mark per mark point declaration of at least 1 array with appropriate identifier … 11 elements (and appropriate data type(s)) Example program code: Public static String[][] FileData = new String[10][2]; VB.NET Dim FileData(0 To 9, 0 To 1) As String Python FileData = [[""] *2 for i in range(11)] #string

1(b)

Python def ReadHighScores(): Filename = "HighScore.txt" File = open(Filename, 'r') for x in range(0, 10): FileData[x][0] = File.readline()[:3] FileData[x][1] = File.readline() File.close VB.NET Sub ReadHighScores() Dim Textfile As String = "HighScore.txt" Dim FileReader As New System.IO.StreamReader(textfile) Dim DataEntered As Integer = 0 While FileReader.Peek <> -1 and DataEntered < 10 FileData(DataEntered, 0) = FileReader.ReadLine() FileData(DataEntered, 1) = FileReader.ReadLine() DataEntered = DataEntered + 1 End While FileReader.Close() End Sub

1(c) [3 marks]

1 mark per mark point procedure heading and end looping through all data structure elements outputting player name, space, score. Each player must start on a new line Example program code: public static void OutputHighScores(){ for(Integer x = 0; x < 11; x++){ System.out.println(FileData[x][0] + " " + FileData[x][1]); Python def OutputHighScores (): for x in range(0, 11): Output = FileData[x][0] + " " + FileData[x][1] print(Output) VB.NET Sub OutputHighScores () For x = 0 To 10 Console.WriteLine(FileData(x, 0) & " " & FileData(x,1)) Next End Sub

1(d)(i) [2 marks]

1 mark per mark point (Main program) calls ReadHighScores() … then calls OutputHighScores() Example program code: public static void main(String[] args){ ReadHighScores(); OutputHighScores(); Python ReadHighScores() OutputHighScore() VB.NET Sub Main() ReadHighScores() OutputHighScore() Console.ReadLine() End Sub

1(d)(ii) [1 mark]

1 mark for screenshot showing the 10 names and scores from the file (and one extra blank space may, or may not be included)

1(e)(i)

VB.NET Console.WriteLine("Enter Username") Username = "ABCD" While Username.length <> 3 Username = Console.ReadLine() End While Score = -1 While Score < 1 Or Score > 100000 Console.WriteLine("Enter score") Score = Console.ReadLine() End While

1(e)(ii)

VB.NET Sub Arrange(Username, Score) Dim Temp1 As String Dim Temp2 As String Dim Second1 As String Dim Second2 As String For x = 0 To 9 If Score > Integer.Parse(FileData(x, 1)) Then Temp1 = FileData(x, 0) Temp2 = FileData(x, 1) FileData(x, 0) = Username FileData(x, 1) = Score.ToString For Count = x + 1 To 9 Second1 = FileData(Count, 0) Second2 = FileData(Count, 1) FileData(Count, 0) = Temp1 FileData(Count, 1) = Temp2 Temp1 = Second1 Temp2 = Second2 x = 10 Next End If Next End Sub

1(e)(iii)

VB.NET OutputHighScore() Username = Console.ReadLine() Score = -1 While(score < 0 or Score > 100000) Score = Console.ReadLine() End While Arrange(Username, Score) OutputHighScore()

1(e)(iv) [1 mark]

1 mark for screenshot. JKL, 9999 entered. After shows JKL in the second position.

1(f)

VB.NET Sub WriteTopTen() Dim Filename As String = " NewHighScore.txt" Dim NewFile As New System.IO.StreamWriter(Filename) For x = 0 To 9 NewFile.WriteLine(FileData(x, 0)) NewFile.WriteLine(FileData(x, 1)) Next NewFile.Close() End Sub

Q2
Oct/Nov 2021 Paper 3 v1

Draw one line from each programming paradigm to its most appropriate description.

Programming paradigm

Declarative

Imperative

Low-level

Object-oriented

Description

Programs using the instruction set of a processor

Programs based on events such as user actions or sensor outputs

Programs using the concepts of class, inheritance, encapsulation and polymorphism

Programs with an explicit sequence of commands that update the program state, with or without procedure calls

Programs that specify the desired result rather than how to get to it 4 marks

Draw **one** line from each programming paradigm to its **most appropriate** description. **Programming paradigm** Declarative Imperative Low-level Object-oriented **Description** Programs using the instruction set of a processor Programs based on events such as user actions or sensor outputs Programs using the concepts of class, inheritance, encapsulation and polymorphism Programs with an explicit sequence of commands that update the program state, with or without procedure calls Programs that specify the desired result rather than how to get to it <span class="part-marks">4 marks</span>
Show mark scheme

2 One mark for each single correct line from Programming Paradigm to Description Programming Paradigm Description Programs using the instruction set of a processor Declarative Programs based on events such as user actions or sensor outputs Imperative Programs using the concepts of class, inheritance, encapsulation and polymorphism Low-level Programs with an explicit sequence of commands that update the program state, with or without procedure calls Object oriented Programs that specify the desired result rather than how to get to it

Q2
Oct/Nov 2021 Paper 3 v2

Draw one line from each programming paradigm to its most appropriate description.

Programming paradigm

Declarative

Imperative

Low-level

Object-oriented

Description

Programs using the instruction set of a processor

Programs based on events such as user actions or sensor outputs

Programs using the concepts of class, inheritance, encapsulation and polymorphism

Programs with an explicit sequence of commands that update the program state, with or without procedure calls

Programs that specify the desired result rather than how to get to it 4 marks

Draw **one** line from each programming paradigm to its **most appropriate** description. **Programming paradigm** Declarative Imperative Low-level Object-oriented **Description** Programs using the instruction set of a processor Programs based on events such as user actions or sensor outputs Programs using the concepts of class, inheritance, encapsulation and polymorphism Programs with an explicit sequence of commands that update the program state, with or without procedure calls Programs that specify the desired result rather than how to get to it <span class="part-marks">4 marks</span>
Show mark scheme

2 One mark for each single correct line from Programming Paradigm to Description Programming Paradigm Description Programs using the instruction set of a processor Declarative Programs based on events such as user actions or sensor outputs Imperative Programs using the concepts of class, inheritance, encapsulation and polymorphism Low-level Programs with an explicit sequence of commands that update the program state, with or without procedure calls Object oriented Programs that specify the desired result rather than how to get to it

Q2
Oct/Nov 2021 Paper 4 v1

A program, written using object-oriented programming, stores pictures as objects.

The program stores the dimensions of the picture (width and height), the colour of the frame (e.g. black), and a description of the picture (e.g. flowers).

The class has the following attributes and methods. Picture
Picture Picture
Description : STRING
Width : INTEGER
Height : INTEGER
FrameColour : STRING
// stores a description of the picture
// stores the width e.g. 30
// stores the height e.g. 40
// stores the colour e.g. black
Constructor()
GetDescription()
GetHeight()
GetWidth()
GetColour()
SetDescription()
// takes all four values as parameters and
sets them to the private attributes
// returns the description of the picture
// returns the height
// returns the width
// returns the frame colour
// takes the new description as a parameter
and writes the value to description

(a) The constructor takes the picture description, frame colour, height, and width as parameters and sets these to the private attributes. 5 marks

Write the program code to declare the class Picture and its constructor. Do not write any other methods.

Use your language appropriate constructor. All attributes should be private.

If you are writing in Python programming language, include attribute declarations using comments.

Save your program as question 2 .

Copy and paste the program code into part 2(a) in the evidence document.

(b) The four get methods return the associated attribute, for example, GetDescription() returns the description of the picture. 3 marks

Write the four get methods.

Save your program.

Copy and paste the program code into part 2(b) in the evidence document.

(c) The method SetDescription() takes a new description as a parameter, and writes this value to the appropriate attribute. 2 marks

Write the method SetDescription() .

Save your program.

Copy and paste the program code into part 2(c) in the evidence document.

(d) Write program code to declare an array of type Picture with 100 elements. 1 mark

Save your program.

Copy and paste the program code into part 2(d) in the evidence document.

(e) The text file Pictures.txt stores the data for the pictures in the order: description, width, height, colour. 8 marks

For example, for the first picture in the text file:

Flowers is the description 45 is the width 50 is the height black is the frame colour.

The data read into the program from the text file is stored in an array of type Picture . The main program and the function will need to access the array data.

The function ReadData() :

  • opens the file Pictures.txt

  • reads the data from the file

  • creates a new object of type Picture for each picture

  • writes each object to the array

  • raises an exception if the file cannot be found

  • counts and returns the number of pictures in the array.

Write program code for the function ReadData() .

Save your program.

Copy and paste the program code into part 2(e) in the evidence document.

(f) The main program calls the function ReadData() . 2 marks

Write the main program.

Save your program.

Copy and paste the program code into part 2(f) in the evidence document.

(g) The main program needs to ask the user to input their requirements for a picture. The user will enter the colour of the frame, the maximum width, and the maximum height of the picture. 7 marks

The program will then search the array of pictures, and output the picture description, the width, and the height of any picture that meets the user’s requirements.

The program should allow the user to input the colour in any case (e.g. Silver, silver, or SILVER), and still output the correct results.

Edit the main program to perform the described actions.

Save your program.

Copy and paste the program code into part 2(g) in the evidence document.

(h) Test your program by inputting the following search criteria: 2 marks

  • BLACK, 100, 100

  • silver, 25, 25

Take screenshots to show the output for both search criteria.

Copy and paste the screenshots into part 2(h) in the evidence document.

A program, written using object-oriented programming, stores pictures as objects. The program stores the dimensions of the picture (width and height), the colour of the frame (e.g. black), and a description of the picture (e.g. flowers). |The class has the following attributes and methods. Picture|| |---|---| |**`Picture`**|**`Picture`**| |`Description : STRING`<br>`Width : INTEGER`<br>`Height : INTEGER`<br>`FrameColour : STRING`|`// stores a description of the picture`<br>`// stores the width e.g. 30`<br>`// stores the height e.g. 40`<br>`// stores the colour e.g. black`| |`Constructor()`<br>`GetDescription()`<br>`GetHeight()`<br>`GetWidth()`<br>`GetColour()`<br>`SetDescription()`|`// takes all four values as parameters and`<br>`sets them to the private attributes`<br>`// returns the description of the picture`<br>`// returns the height`<br>`// returns the width`<br>`// returns the frame colour`<br>`// takes the new description as a parameter`<br>`and writes the value to description`| ### (a) The constructor takes the picture description, frame colour, height, and width as parameters and sets these to the private attributes. <span class="part-marks">5 marks</span> Write the program code to declare the class `Picture` and its constructor. Do not write any other methods. Use your language appropriate constructor. All attributes should be private. If you are writing in Python programming language, include attribute declarations using comments. Save your program as **question 2** . Copy and paste the program code into **part 2(a)** in the evidence document. ### (b) The four get methods return the associated attribute, for example, `GetDescription()` returns the description of the picture. <span class="part-marks">3 marks</span> Write the **four** get methods. Save your program. Copy and paste the program code into **part 2(b)** in the evidence document. ### (c) The method `SetDescription()` takes a new description as a parameter, and writes this value to the appropriate attribute. <span class="part-marks">2 marks</span> Write the method `SetDescription()` . Save your program. Copy and paste the program code into **part 2(c)** in the evidence document. ### (d) Write program code to declare an array of type `Picture` with 100 elements. <span class="part-marks">1 mark</span> Save your program. Copy and paste the program code into **part 2(d)** in the evidence document. ### (e) The text file `Pictures.txt` stores the data for the pictures in the order: description, width, height, colour. <span class="part-marks">8 marks</span> For example, for the first picture in the text file: `Flowers` is the description `45` is the width `50` is the height `black` is the frame colour. The data read into the program from the text file is stored in an array of type `Picture` . The main program and the function will need to access the array data. The function `ReadData()` : - opens the file `Pictures.txt` - reads the data from the file - creates a new object of type `Picture` for each picture - writes each object to the array - raises an exception if the file cannot be found - counts and returns the number of pictures in the array. Write program code for the function `ReadData()` . Save your program. Copy and paste the program code into **part 2(e)** in the evidence document. ### (f) The main program calls the function `ReadData()` . <span class="part-marks">2 marks</span> Write the main program. Save your program. Copy and paste the program code into **part 2(f)** in the evidence document. ### (g) The main program needs to ask the user to input their requirements for a picture. The user will enter the colour of the frame, the maximum width, and the maximum height of the picture. <span class="part-marks">7 marks</span> The program will then search the array of pictures, and output the picture description, the width, and the height of any picture that meets the user’s requirements. The program should allow the user to input the colour in any case (e.g. Silver, silver, or SILVER), and still output the correct results. Edit the main program to perform the described actions. Save your program. Copy and paste the program code into **part 2(g)** in the evidence document. ### (h) Test your program by inputting the following search criteria: <span class="part-marks">2 marks</span> - BLACK, 100, 100 - silver, 25, 25 Take screenshots to show the output for both search criteria. Copy and paste the screenshots into **part 2(h)** in the evidence document.
Show mark scheme

2(a) [3 marks]

VB.NET Class Picture Private Description As String Private Width As Integer Private Height As Integer Private FrameColour As String Public Sub New(DescriptionP, WidthP, HeightP,FrameColourP) Description = DescriptionP Width = WidthP Height = HeightP FrameColour = FrameColourP End Sub End Class

2(b) [2 marks]

1 mark per bullet point 1 Get method taking no parameter… • …returning correct attribute • remaining 3 correct methods • Example program code: Python def GetDescription(self): return self.__Description def GetWidth(self): return self.__Width def GetHeight(self): return self.__Height def GetColour(self): return self.__FrameColour Java public String GetDescription(){ return Description; } public Integer GetWidth(){ return Width; } public Integer GetHeight(){ return Height; } public String GetFrameColour(){ return FrameColour; } VB.NET Function GetDescription() Return Description End Function Function GetWidth() Return Width End Function Function GetHeight() Return Height End Function Function GetFrameColour() Return FrameColour End Function

2(c) [1 mark]

1 mark per bullet point Set method (procedure) taking parameter (no return) … • …assigning parameter to correct attribute • Example program code: Python def SetDescription(self, DescriptionP): self.__Description = DescriptionP Java public void SetDescription(String DescriptionP){ Description = DescriptionP; } VB.NET Public Sub SetDescription(DescriptionP) Description = DescriptionP End Sub

2(d) [8 marks]

1 mark for declaring array of type with 100 elements Picture Example program code: Python PictureArray = [] for i in range(100): PictureArray.append(Picture("",0,0,"")) Java public static void main(String[] args){ } Picture[] PictureArray = new Picture[100]; VB.NET Dim PictureArray(0 to 99) As Picture

2(e)

Java public static Integer ReadData(Picture[] PictureArray){ String Filename = "Pictures.txt"; String DataRead; String Description; String Width; String Height; String FrameColour; Integer NumberPictures = 0; try{ FileReader f = new FileReader(Filename); BufferedReader Reader = new BufferedReader(f); DataRead = Reader.readLine(); while(DataRead != null){ Description = DataRead; Width = Reader.readLine(); Height = Reader.readLine(); FrameColour = Reader.readLine(); PictureArray[NumberPictures] = new Picture(Description, Integer.parseInt(Width), Integer.parseInt(Height), FrameColour); NumberPictures++; DataRead = Reader.readLine(); } Reader.close(); } catch(FileNotFoundException ex){ System.out.println("No File found"); } catch(IOException ex){ System.out.println("No File found"); } return NumberPictures; }

2(f) [7 marks]

1 mark per bullet point calling function … • ReadData() …store/use the Number of elements returned/by reference based on answer • to part 2e Example program code: Python NumberPicturesInArray, PictureArray = ReadData(PictureArray) Java Integer NumberPicturesInArray = ReadData(PictureArray); VB.NET Dim NumberPicturesInArray As Integer = ReadData()

2(g) [2 marks]

Console.WriteLine(PictureArray(X).GetDescription() & " " & PictureArray(X).GetWidth() & " " & PictureArray(X).GetHeight) End If Next Console.ReadLine() End Sub Java public static void main(String[] args){ Picture[] PictureArray = new Picture[100]; Integer NumberPicturesInArray = ReadData(PictureArray); Scanner scanner = new Scanner(System.in); System.out.println("Enter the Frame colour"); String FrameColour = scanner.nextLine(); System.out.println("Enter the Maximum Width"); Integer MaxWidth = Integer.parseInt(scanner.nextLine()); System.out.println("Enter the Maximum Height"); Integer MaxHeight = Integer.parseInt(scanner.nextLine()); FrameColour = FrameColour.toLowerCase(); for(int X = 0; X < NumberPicturesInArray; X++){ if(PictureArray[X].GetFrameColour().equals(FrameColour) && PictureArray[X].GetWidth() <= MaxWidth && PictureArray[X].GetHeight() <= MaxHeight){ System.out.println(PictureArray[X].GetDescription() + " " + PictureArray[X].GetWidth() + " " + PictureArray[X].GetHeight()); } } }

2(h) [4 marks]

1 mark for screenshot showing output for BLACK, 100, 100 1 mark for showing no outputs for silver, 25, 25 Input the Frame colour BLACK Input the Maximum Width 100 Input the Maximum Height 100 Matches Frames shown flowers 45 50 people 20 20 landscape 30 45 landscape 25 37 people 50 40 Input the Frame colour silver Input the Maximum Width 25 Input the Maximum Height 25 Matches Frames shown

Q2
Oct/Nov 2021 Paper 4 v2

A program, written using object-oriented programming, stores pictures as objects.

The program stores the dimensions of the picture (width and height), the colour of the frame (e.g. black), and a description of the picture (e.g. flowers).

The class has the following attributes and methods. Picture
Picture Picture
Description : STRING
Width : INTEGER
Height : INTEGER
FrameColour : STRING
// stores a description of the picture
// stores the width e.g. 30
// stores the height e.g. 40
// stores the colour e.g. black
Constructor()
GetDescription()
GetHeight()
GetWidth()
GetColour()
SetDescription()
// takes all four values as parameters and
sets them to the private attributes
// returns the description of the picture
// returns the height
// returns the width
// returns the frame colour
// takes the new description as a parameter
and writes the value to description

(a) The constructor takes the picture description, frame colour, height, and width as parameters and sets these to the private attributes. 5 marks

Write the program code to declare the class Picture and its constructor. Do not write any other methods.

Use your language appropriate constructor. All attributes should be private.

If you are writing in Python programming language, include attribute declarations using comments.

Save your program as question 2 .

Copy and paste the program code into part 2(a) in the evidence document.

(b) The four get methods return the associated attribute, for example, GetDescription() returns the description of the picture. 3 marks

Write the four get methods.

Save your program.

Copy and paste the program code into part 2(b) in the evidence document.

(c) The method SetDescription() takes a new description as a parameter, and writes this value to the appropriate attribute. 2 marks

Write the method SetDescription() .

Save your program.

Copy and paste the program code into part 2(c) in the evidence document.

(d) Write program code to declare an array of type Picture with 100 elements. 1 mark

Save your program.

Copy and paste the program code into part 2(d) in the evidence document.

(e) The text file Pictures.txt stores the data for the pictures in the order: description, width, height, colour. 8 marks

For example, for the first picture in the text file:

Flowers is the description 45 is the width 50 is the height black is the frame colour.

The data read into the program from the text file is stored in an array of type Picture . The main program and the function will need to access the array data.

The function ReadData() :

  • opens the file Pictures.txt

  • reads the data from the file

  • creates a new object of type Picture for each picture

  • writes each object to the array

  • raises an exception if the file cannot be found

  • counts and returns the number of pictures in the array.

Write program code for the function ReadData() .

Save your program.

Copy and paste the program code into part 2(e) in the evidence document.

(f) The main program calls the function ReadData() . 2 marks

Write the main program.

Save your program.

Copy and paste the program code into part 2(f) in the evidence document.

(g) The main program needs to ask the user to input their requirements for a picture. The user will enter the colour of the frame, the maximum width, and the maximum height of the picture. 7 marks

The program will then search the array of pictures, and output the picture description, the width, and the height of any picture that meets the user’s requirements.

The program should allow the user to input the colour in any case (e.g. Silver, silver, or SILVER), and still output the correct results.

Edit the main program to perform the described actions.

Save your program.

Copy and paste the program code into part 2(g) in the evidence document.

(h) Test your program by inputting the following search criteria: 2 marks

  • BLACK, 100, 100

  • silver, 25, 25

Take screenshots to show the output for both search criteria.

Copy and paste the screenshots into part 2(h) in the evidence document.

A program, written using object-oriented programming, stores pictures as objects. The program stores the dimensions of the picture (width and height), the colour of the frame (e.g. black), and a description of the picture (e.g. flowers). |The class has the following attributes and methods. Picture|| |---|---| |**`Picture`**|**`Picture`**| |`Description : STRING`<br>`Width : INTEGER`<br>`Height : INTEGER`<br>`FrameColour : STRING`|`// stores a description of the picture`<br>`// stores the width e.g. 30`<br>`// stores the height e.g. 40`<br>`// stores the colour e.g. black`| |`Constructor()`<br>`GetDescription()`<br>`GetHeight()`<br>`GetWidth()`<br>`GetColour()`<br>`SetDescription()`|`// takes all four values as parameters and`<br>`sets them to the private attributes`<br>`// returns the description of the picture`<br>`// returns the height`<br>`// returns the width`<br>`// returns the frame colour`<br>`// takes the new description as a parameter`<br>`and writes the value to description`| ### (a) The constructor takes the picture description, frame colour, height, and width as parameters and sets these to the private attributes. <span class="part-marks">5 marks</span> Write the program code to declare the class `Picture` and its constructor. Do not write any other methods. Use your language appropriate constructor. All attributes should be private. If you are writing in Python programming language, include attribute declarations using comments. Save your program as **question 2** . Copy and paste the program code into **part 2(a)** in the evidence document. ### (b) The four get methods return the associated attribute, for example, `GetDescription()` returns the description of the picture. <span class="part-marks">3 marks</span> Write the **four** get methods. Save your program. Copy and paste the program code into **part 2(b)** in the evidence document. ### (c) The method `SetDescription()` takes a new description as a parameter, and writes this value to the appropriate attribute. <span class="part-marks">2 marks</span> Write the method `SetDescription()` . Save your program. Copy and paste the program code into **part 2(c)** in the evidence document. ### (d) Write program code to declare an array of type `Picture` with 100 elements. <span class="part-marks">1 mark</span> Save your program. Copy and paste the program code into **part 2(d)** in the evidence document. ### (e) The text file `Pictures.txt` stores the data for the pictures in the order: description, width, height, colour. <span class="part-marks">8 marks</span> For example, for the first picture in the text file: `Flowers` is the description `45` is the width `50` is the height `black` is the frame colour. The data read into the program from the text file is stored in an array of type `Picture` . The main program and the function will need to access the array data. The function `ReadData()` : - opens the file `Pictures.txt` - reads the data from the file - creates a new object of type `Picture` for each picture - writes each object to the array - raises an exception if the file cannot be found - counts and returns the number of pictures in the array. Write program code for the function `ReadData()` . Save your program. Copy and paste the program code into **part 2(e)** in the evidence document. ### (f) The main program calls the function `ReadData()` . <span class="part-marks">2 marks</span> Write the main program. Save your program. Copy and paste the program code into **part 2(f)** in the evidence document. ### (g) The main program needs to ask the user to input their requirements for a picture. The user will enter the colour of the frame, the maximum width, and the maximum height of the picture. <span class="part-marks">7 marks</span> The program will then search the array of pictures, and output the picture description, the width, and the height of any picture that meets the user’s requirements. The program should allow the user to input the colour in any case (e.g. Silver, silver, or SILVER), and still output the correct results. Edit the main program to perform the described actions. Save your program. Copy and paste the program code into **part 2(g)** in the evidence document. ### (h) Test your program by inputting the following search criteria: <span class="part-marks">2 marks</span> - BLACK, 100, 100 - silver, 25, 25 Take screenshots to show the output for both search criteria. Copy and paste the screenshots into **part 2(h)** in the evidence document.
Show mark scheme

2(a) [3 marks]

VB.NET Class Picture Private Description As String Private Width As Integer Private Height As Integer Private FrameColour As String Public Sub New(DescriptionP, WidthP, HeightP,FrameColourP) Description = DescriptionP Width = WidthP Height = HeightP FrameColour = FrameColourP End Sub End Class

2(b) [2 marks]

1 mark per bullet point 1 Get method taking no parameter… • …returning correct attribute • remaining 3 correct methods • Example program code: Python def GetDescription(self): return self.__Description def GetWidth(self): return self.__Width def GetHeight(self): return self.__Height def GetColour(self): return self.__FrameColour Java public String GetDescription(){ return Description; } public Integer GetWidth(){ return Width; } public Integer GetHeight(){ return Height; } public String GetFrameColour(){ return FrameColour; } VB.NET Function GetDescription() Return Description End Function Function GetWidth() Return Width End Function Function GetHeight() Return Height End Function Function GetFrameColour() Return FrameColour End Function

2(c) [1 mark]

1 mark per bullet point Set method (procedure) taking parameter (no return) … • …assigning parameter to correct attribute • Example program code: Python def SetDescription(self, DescriptionP): self.__Description = DescriptionP Java public void SetDescription(String DescriptionP){ Description = DescriptionP; } VB.NET Public Sub SetDescription(DescriptionP) Description = DescriptionP End Sub

2(d) [8 marks]

1 mark for declaring array of type with 100 elements Picture Example program code: Python PictureArray = [] for i in range(100): PictureArray.append(Picture("",0,0,"")) Java public static void main(String[] args){ } Picture[] PictureArray = new Picture[100]; VB.NET Dim PictureArray(0 to 99) As Picture

2(e)

Java public static Integer ReadData(Picture[] PictureArray){ String Filename = "Pictures.txt"; String DataRead; String Description; String Width; String Height; String FrameColour; Integer NumberPictures = 0; try{ FileReader f = new FileReader(Filename); BufferedReader Reader = new BufferedReader(f); DataRead = Reader.readLine(); while(DataRead != null){ Description = DataRead; Width = Reader.readLine(); Height = Reader.readLine(); FrameColour = Reader.readLine(); PictureArray[NumberPictures] = new Picture(Description, Integer.parseInt(Width), Integer.parseInt(Height), FrameColour); NumberPictures++; DataRead = Reader.readLine(); } Reader.close(); } catch(FileNotFoundException ex){ System.out.println("No File found"); } catch(IOException ex){ System.out.println("No File found"); } return NumberPictures; }

2(f) [7 marks]

1 mark per bullet point calling function … • ReadData() …store/use the Number of elements returned/by reference based on answer • to part 2e Example program code: Python NumberPicturesInArray, PictureArray = ReadData(PictureArray) Java Integer NumberPicturesInArray = ReadData(PictureArray); VB.NET Dim NumberPicturesInArray As Integer = ReadData()

2(g) [2 marks]

Console.WriteLine(PictureArray(X).GetDescription() & " " & PictureArray(X).GetWidth() & " " & PictureArray(X).GetHeight) End If Next Console.ReadLine() End Sub Java public static void main(String[] args){ Picture[] PictureArray = new Picture[100]; Integer NumberPicturesInArray = ReadData(PictureArray); Scanner scanner = new Scanner(System.in); System.out.println("Enter the Frame colour"); String FrameColour = scanner.nextLine(); System.out.println("Enter the Maximum Width"); Integer MaxWidth = Integer.parseInt(scanner.nextLine()); System.out.println("Enter the Maximum Height"); Integer MaxHeight = Integer.parseInt(scanner.nextLine()); FrameColour = FrameColour.toLowerCase(); for(int X = 0; X < NumberPicturesInArray; X++){ if(PictureArray[X].GetFrameColour().equals(FrameColour) && PictureArray[X].GetWidth() <= MaxWidth && PictureArray[X].GetHeight() <= MaxHeight){ System.out.println(PictureArray[X].GetDescription() + " " + PictureArray[X].GetWidth() + " " + PictureArray[X].GetHeight()); } } }

2(h) [4 marks]

1 mark for screenshot showing output for BLACK, 100, 100 1 mark for showing no outputs for silver, 25, 25 Input the Frame colour BLACK Input the Maximum Width 100 Input the Maximum Height 100 Matches Frames shown flowers 45 50 people 20 20 landscape 30 45 landscape 25 37 people 50 40 Input the Frame colour silver Input the Maximum Width 25 Input the Maximum Height 25 Matches Frames shown

Q9
May/Jun 2021 Paper 3 v1

(a) Describe what is meant by an imperative (procedural) programming language. 2 marks 2 marks

(b) Describe what is meant by a declarative programming language. 4 marks

(c) Identify the programming paradigm for eac ch of these program code examples.
Program code example Programming paradigm
male(john).
female(ethel).
parent(john, ethel).

FOR Counter = 1 TO 20
X = X * Counter
NEXT Counter

Start: LDD Counter
INC ACC
STO Counter

public class Vehicle
{
private speed;
public Vehicle()
{
speed = 0;
}
}
### (a) Describe what is meant by **an imperative (procedural)** programming language. <span class="part-marks">2 marks</span> <span class="part-marks">2 marks</span> ### (b) Describe what is meant by **a declarative** programming language. <span class="part-marks">4 marks</span> |(c) Identify the programming paradigm for eac|ch of these program code examples.| |---|---| |**Program code example**|**Programming paradigm**| |`male(john).`<br>`female(ethel).`<br>`parent(john, ethel).`|| |<br>`FOR Counter = 1 TO 20`<br>` X = X * Counter`<br>`NEXT Counter`|| |<br>`Start: LDD Counter`<br>` INC ACC`<br>` STO Counter`|| |<br>`public class Vehicle`<br>`{`<br>` private speed;`<br>` public Vehicle()`<br>` {`<br>` speed = 0;`<br>` }`<br>`}`||
Show mark scheme

9(a)

One mark for each correct marking point (Max 2) Imperative languages use variables • … which are changed using (assignment) statements • … they rely on a method of repetition / iteration. • The statements provide a sequence of commands for the computer to • perform … in the order written / given • … each line of code changes something in the program run. •

9(b) [2 marks]

One mark for each correct marking point (Max 2) Instructs a program on what needs to be done instead of how to do it • ... using facts and rules • … using queries to satisfy goals. • Can be logical or functional • Logical - states a program as a set of logical relations • Functional – constructed by applying functions to arguments / uses a • mathematical style

9(c) [4 marks]

One mark for each correct programming paradigm (Max 4) Program code example Programming paradigm male(john). Declarative female(ethel). parent(john, ethel). FOR Counter = 1 TO 20 Procedural / imperative X = X * Counter NEXT Counter Start: LDD Counter Low-level / assembly INC ACC STO Counter public class Vehicle { private speed; public Vehicle() Object oriented / (OOP) { speed = 0; } }

Q9
May/Jun 2021 Paper 3 v2

(a) Describe what is meant by an imperative (procedural) programming language. 2 marks 2 marks

(b) Describe what is meant by a declarative programming language. 4 marks

(c) Identify the programming paradigm for eac ch of these program code examples.
Program code example Programming paradigm
male(john).
female(ethel).
parent(john, ethel).

FOR Counter = 1 TO 20
X = X * Counter
NEXT Counter

Start: LDD Counter
INC ACC
STO Counter

public class Vehicle
{
private speed;
public Vehicle()
{
speed = 0;
}
}
### (a) Describe what is meant by **an imperative (procedural)** programming language. <span class="part-marks">2 marks</span> <span class="part-marks">2 marks</span> ### (b) Describe what is meant by **a declarative** programming language. <span class="part-marks">4 marks</span> |(c) Identify the programming paradigm for eac|ch of these program code examples.| |---|---| |**Program code example**|**Programming paradigm**| |`male(john).`<br>`female(ethel).`<br>`parent(john, ethel).`|| |<br>`FOR Counter = 1 TO 20`<br>` X = X * Counter`<br>`NEXT Counter`|| |<br>`Start: LDD Counter`<br>` INC ACC`<br>` STO Counter`|| |<br>`public class Vehicle`<br>`{`<br>` private speed;`<br>` public Vehicle()`<br>` {`<br>` speed = 0;`<br>` }`<br>`}`||
Show mark scheme

9(a)

One mark for each correct marking point (Max 2) Imperative languages use variables • … which are changed using (assignment) statements • … they rely on a method of repetition / iteration. • The statements provide a sequence of commands for the computer to • perform … in the order written / given • … each line of code changes something in the program run. •

9(b) [2 marks]

One mark for each correct marking point (Max 2) Instructs a program on what needs to be done instead of how to do it • ... using facts and rules • … using queries to satisfy goals. • Can be logical or functional • Logical - states a program as a set of logical relations • Functional – constructed by applying functions to arguments / uses a • mathematical style

9(c) [4 marks]

One mark for each correct programming paradigm (Max 4) Program code example Programming paradigm male(john). Declarative female(ethel). parent(john, ethel). FOR Counter = 1 TO 20 Procedural / imperative X = X * Counter NEXT Counter Start: LDD Counter Low-level / assembly INC ACC STO Counter public class Vehicle { private speed; public Vehicle() Object oriented / (OOP) { speed = 0; } }

Q9
May/Jun 2021 Paper 3 v3

(a) Describe what is meant by an imperative (procedural) programming language. 2 marks 2 marks

(b) Describe what is meant by a declarative programming language. 4 marks

(c) Identify the programming paradigm for eac ch of these program code examples.
Program code example Programming paradigm
male(john).
female(ethel).
parent(john, ethel).

FOR Counter = 1 TO 20
X = X * Counter
NEXT Counter

Start: LDD Counter
INC ACC
STO Counter

public class Vehicle
{
private speed;
public Vehicle()
{
speed = 0;
}
}
### (a) Describe what is meant by **an imperative (procedural)** programming language. <span class="part-marks">2 marks</span> <span class="part-marks">2 marks</span> ### (b) Describe what is meant by **a declarative** programming language. <span class="part-marks">4 marks</span> |(c) Identify the programming paradigm for eac|ch of these program code examples.| |---|---| |**Program code example**|**Programming paradigm**| |`male(john).`<br>`female(ethel).`<br>`parent(john, ethel).`|| |<br>`FOR Counter = 1 TO 20`<br>` X = X * Counter`<br>`NEXT Counter`|| |<br>`Start: LDD Counter`<br>` INC ACC`<br>` STO Counter`|| |<br>`public class Vehicle`<br>`{`<br>` private speed;`<br>` public Vehicle()`<br>` {`<br>` speed = 0;`<br>` }`<br>`}`||
Show mark scheme

9(a)

One mark for each correct marking point (Max 2) Imperative languages use variables • … which are changed using (assignment) statements • … they rely on a method of repetition / iteration. • The statements provide a sequence of commands for the computer to • perform … in the order written / given • … each line of code changes something in the program run. •

9(b) [2 marks]

One mark for each correct marking point (Max 2) Instructs a program on what needs to be done instead of how to do it • ... using facts and rules • … using queries to satisfy goals. • Can be logical or functional • Logical - states a program as a set of logical relations • Functional – constructed by applying functions to arguments / uses a • mathematical style

9(c) [4 marks]

One mark for each correct programming paradigm (Max 4) Program code example Programming paradigm male(john). Declarative female(ethel). parent(john, ethel). FOR Counter = 1 TO 20 Procedural / imperative X = X * Counter NEXT Counter Start: LDD Counter Low-level / assembly INC ACC STO Counter public class Vehicle { private speed; public Vehicle() Object oriented / (OOP) { speed = 0; } }

Q3
May/Jun 2021 Paper 4 v1

A computer game requires users to travel around a world to find and open treasure chests. Each treasure chest has a mathematics question inside. The user enters the answer. The number of points awarded depends on the number of attempts before the user gives the correct answer.

The program will be created using object-oriented programming (OOP).

The following class diagram describes the class TreasureChest.
TreasureChest TreasureChest
question : STRING
answer : INTEGER
points : INTEGER
// stores the question
// stores the answer
// stores the maximum possible number of
points available for this chest
constructor()
getQuestion()
checkAnswer()
getPoints()

// takes question, answer and points as
parameters and creates an instance of an
object
// returns the question
// takes the user’s answer as a parameter and
returns True if it is correct,
otherwise returns False
// takes the number of attempts as a
parameter and returns the number of
points awarded

(a) Create a new program. 5 marks

Write program code to declare the class TreasureChest .

Do not write any other methods.

The attributes are private.

If you are using the Python programming language, include attribute declarations using comments.

Save your program as question3 .

Copy and paste the program code into part 3(a) in the evidence document.

(b) The text file TreasureChestData.txt stores data for five questions, in the order of question, answer, points. 8 marks

For example, the first three lines of the file are for the first question:

2*2 question 4 answer 10 points

Write program code for the procedure, readData() to:

  • read each question, answer and points from the text file

  • create an object of type TreasureChest for each question

  • declare an array named arrayTreasure of type TreasureChest

  • append each object to the array

  • use exception handling to output an appropriate message if the file is not found.

Save your program.

Copy and paste the program code into part 3(b) in the evidence document.

(c) The main program repeats each question until the user inputs the correct answer. The number of points awarded depends on the number of attempts before the user gives the correct answer.

(i) The class TreasureChest has a method getQuestion() that returns the question. 1 mark

Write the method getQuestion() .

Save your program.

Copy and paste the program code into part 3(c)(i) in the evidence document.

(ii) The class TreasureChest has a method checkAnswer() that takes the user’s answer as a parameter. It returns True if the answer is correct and False otherwise. 3 marks

Write the method checkAnswer() .

Save your program.

Copy and paste the program code into part 3(c)(ii) in the evidence document.

(iii) The class TreasureChest has a method getPoints() that takes the number of attempts as a parameter. 5 marks

  • If the number of attempts is 1, it returns the value of points .

  • If the number of attempts is 2, it returns the integer value of points divided by 2 ( DIV 2 ).

  • If the number of attempts is 3 or 4, it returns the integer value of points divided by 4 ( DIV 4 ).

  • If the number of attempts is not 1 or 2 or 3 or 4, it returns 0 (zero).

For example, a question is worth 100 points and the user took 2 attempts to give the correct answer. The user is awarded 50 points (100 DIV 2).

Write the method getPoints() .

Save your program.

Copy and paste the program code into part 3(c)(iii) in the evidence document.

(iv) Write program code for the main program to: 7 marks

  • call the procedure readData()

  • ask the user to enter a question number between 1 and 5

  • output the question that matches the question number entered by the user

  • check if the answer input by the user is correct using the method checkAnswer()

  • repeat the question until the user inputs the correct answer

  • count how many times the user attempted the question

  • use the method getPoints() to return the number of points awarded

  • output the number of points the user is awarded.

Save your program.

Copy and paste the program code into part 3(c)(iv) in the evidence document.

(v) Test the program. 2 marks

Take a screenshot showing the input(s) and output(s) for each of the following two tests.

In the first test:

  • select question 1 and answer it correctly the first time.

In the second test:

  • select question 5 and answer it correctly the second time.

Save your program.

Copy and paste the screenshots into part 3(c)(v) in the evidence document.

A computer game requires users to travel around a world to find and open treasure chests. Each treasure chest has a mathematics question inside. The user enters the answer. The number of points awarded depends on the number of attempts before the user gives the correct answer. The program will be created using object-oriented programming (OOP). |The following class diagram describes the class TreasureChest.|| |---|---| |`TreasureChest`|`TreasureChest`| |`question : STRING`<br>`answer : INTEGER`<br>`points : INTEGER`|`// stores the question`<br>`// stores the answer`<br>`// stores the maximum possible number of`<br>`points available for this chest`| |`constructor()`<br>`getQuestion()`<br>`checkAnswer()`<br>`getPoints()`|<br>`// takes question, answer and points as`<br>`parameters and creates an instance of an`<br>`object`<br>`// returns the question`<br>`// takes the user’s answer as a parameter and`<br>`returns True if it is correct,`<br>`otherwise returns False`<br>`// takes the number of attempts as a`<br>`parameter and returns the number of`<br>`points awarded`| ### (a) Create a new program. <span class="part-marks">5 marks</span> Write program code to declare the class `TreasureChest` . Do **not** write any other methods. The attributes are private. If you are using the Python programming language, include attribute declarations using comments. Save your program as **question3** . Copy and paste the program code into **part 3(a)** in the evidence document. ### (b) The text file `TreasureChestData.txt` stores data for five questions, in the order of question, answer, points. <span class="part-marks">8 marks</span> For example, the first three lines of the file are for the first question: `2*2` question `4` answer `10` points Write program code for the procedure, `readData()` to: - read each question, answer and points from the text file - create an object of type `TreasureChest` for each question - declare an array named `arrayTreasure` of type `TreasureChest` - append each object to the array - use exception handling to output an appropriate message if the file is not found. Save your program. Copy and paste the program code into **part 3(b)** in the evidence document. ### (c) The main program repeats each question until the user inputs the correct answer. The number of points awarded depends on the number of attempts before the user gives the correct answer. #### (i) The class `TreasureChest` has a method `getQuestion()` that returns the question. <span class="part-marks">1 mark</span> Write the method `getQuestion()` . Save your program. Copy and paste the program code into **part 3(c)(i)** in the evidence document. #### (ii) The class `TreasureChest` has a method `checkAnswer()` that takes the user’s answer as a parameter. It returns `True` if the answer is correct and `False` otherwise. <span class="part-marks">3 marks</span> Write the method `checkAnswer()` . Save your program. Copy and paste the program code into **part 3(c)(ii)** in the evidence document. #### (iii) The class `TreasureChest` has a method `getPoints()` that takes the number of attempts as a parameter. <span class="part-marks">5 marks</span> - If the number of attempts is 1, it returns the value of `points` . - If the number of attempts is 2, it returns the integer value of `points` divided by 2 ( `DIV 2` ). - If the number of attempts is 3 or 4, it returns the integer value of `points` divided by 4 ( `DIV 4` ). - If the number of attempts is not 1 or 2 or 3 or 4, it returns `0` (zero). For example, a question is worth 100 points and the user took 2 attempts to give the correct answer. The user is awarded 50 points (100 DIV 2). Write the method `getPoints()` . Save your program. Copy and paste the program code into **part 3(c)(iii)** in the evidence document. #### (iv) Write program code for the main program to: <span class="part-marks">7 marks</span> - call the procedure `readData()` - ask the user to enter a question number between 1 and 5 - output the question that matches the question number entered by the user - check if the answer input by the user is correct using the method `checkAnswer()` - repeat the question until the user inputs the correct answer - count how many times the user attempted the question - use the method `getPoints()` to return the number of points awarded - output the number of points the user is awarded. Save your program. Copy and paste the program code into **part 3(c)(iv)** in the evidence document. #### (v) Test the program. <span class="part-marks">2 marks</span> Take a screenshot showing the input(s) and output(s) for each of the following two tests. In the first test: - select question 1 and answer it correctly the first time. In the second test: - select question 5 and answer it correctly the second time. Save your program. Copy and paste the screenshots into **part 3(c)(v)** in the evidence document.
Show mark scheme

3(a)

import java.util.Scanner; class treasureChest{ private String question; private Integer answer; private Integer points; public treasureChest(String questionP, Integer answerP, Integer pointsP){ question = questionP; answer = answerP; points = pointsP; }

3(b)

catch(FileNotFoundException ex){ System.out.println("No file found"); } catch(IOException ex){ System.out.println("No file found"); }

3(c)(i) [1 mark]

1 mark for returning the value of question Example code: Visual Basic Return question End Function Python return self.__question return question;

3(c)(ii) [3 marks]

1 mark per bullet point Comparing parameter to that object ’ s answer… …returning True if correct and False otherwise Example code: Visual Basic If answer = answerP Then Return True Else Return False End If End Function Python if int(self.__answer) == answerP: return True else: return False if (answer == answerP){ return true; }else{ return false; }

3(c)(iii)

public Integer getPoints(Integer attempts){ if (attempts == 1){ return points; }else if(attempts == 2){ return Math.round(points/2); }else if(attempts == 3 || attempts == 4){ return Math.round(points/4); }else{ return 0; }

3(c)(iv)

public static void main(String[] args){ readData(); Scanner scanner = new Scanner(System.in); System.out.println("Pick a treasure chest to open"); Integer answer; Integer choice; choice= Integer.parseInt(scanner.nextLine()); Integer attempts; if (choice> 0 && choice < 6){ Boolean result = false; attempts = 0; while (result == false){ answer = Integer.parseInt(scanner.nextLine()); attempts++; } System.out.println(arrayTreasure[choice-1].getPoints(attempts)); }

3(c)(v) [2 marks]

1 mark per screenshot Screenshot: outputting 2*2 entering 4 outputting 10 Screenshot: outputting 3000+4000 entering an incorrect value entering 7000 outputting 9

Q3
May/Jun 2021 Paper 4 v2

A computer game requires users to travel around a world to find and open treasure chests. Each treasure chest has a mathematics question inside. The user enters the answer. The number of points awarded depends on the number of attempts before the user gives the correct answer.

The program will be created using object-oriented programming (OOP).

The following class diagram describes the class TreasureChest.
TreasureChest TreasureChest
question : STRING
answer : INTEGER
points : INTEGER
// stores the question
// stores the answer
// stores the maximum possible number of
points available for this chest
constructor()
getQuestion()
checkAnswer()
getPoints()

// takes question, answer and points as
parameters and creates an instance of an
object
// returns the question
// takes the user’s answer as a parameter and
returns True if it is correct,
otherwise returns False
// takes the number of attempts as a
parameter and returns the number of
points awarded

(a) Create a new program. 5 marks

Write program code to declare the class TreasureChest .

Do not write any other methods.

The attributes are private.

If you are using the Python programming language, include attribute declarations using comments.

Save your program as question3 .

Copy and paste the program code into part 3(a) in the evidence document.

(b) The text file TreasureChestData.txt stores data for five questions, in the order of question, answer, points. 8 marks

For example, the first three lines of the file are for the first question:

2*2 question 4 answer 10 points

Write program code for the procedure, readData() to:

  • read each question, answer and points from the text file

  • create an object of type TreasureChest for each question

  • declare an array named arrayTreasure of type TreasureChest

  • append each object to the array

  • use exception handling to output an appropriate message if the file is not found.

Save your program.

Copy and paste the program code into part 3(b) in the evidence document.

(c) The main program repeats each question until the user inputs the correct answer. The number of points awarded depends on the number of attempts before the user gives the correct answer.

(i) The class TreasureChest has a method getQuestion() that returns the question. 1 mark

Write the method getQuestion() .

Save your program.

Copy and paste the program code into part 3(c)(i) in the evidence document.

(ii) The class TreasureChest has a method checkAnswer() that takes the user’s answer as a parameter. It returns True if the answer is correct and False otherwise. 3 marks

Write the method checkAnswer() .

Save your program.

Copy and paste the program code into part 3(c)(ii) in the evidence document.

(iii) The class TreasureChest has a method getPoints() that takes the number of attempts as a parameter. 5 marks

  • If the number of attempts is 1, it returns the value of points .

  • If the number of attempts is 2, it returns the integer value of points divided by 2 ( DIV 2 ).

  • If the number of attempts is 3 or 4, it returns the integer value of points divided by 4 ( DIV 4 ).

  • If the number of attempts is not 1 or 2 or 3 or 4, it returns 0 (zero).

For example, a question is worth 100 points and the user took 2 attempts to give the correct answer. The user is awarded 50 points (100 DIV 2).

Write the method getPoints() .

Save your program.

Copy and paste the program code into part 3(c)(iii) in the evidence document.

(iv) Write program code for the main program to: 7 marks

  • call the procedure readData()

  • ask the user to enter a question number between 1 and 5

  • output the question that matches the question number entered by the user

  • check if the answer input by the user is correct using the method checkAnswer()

  • repeat the question until the user inputs the correct answer

  • count how many times the user attempted the question

  • use the method getPoints() to return the number of points awarded

  • output the number of points the user is awarded.

Save your program.

Copy and paste the program code into part 3(c)(iv) in the evidence document.

(v) Test the program. 2 marks

Take a screenshot showing the input(s) and output(s) for each of the following two tests.

In the first test:

  • select question 1 and answer it correctly the first time.

In the second test:

  • select question 5 and answer it correctly the second time.

Save your program.

Copy and paste the screenshots into part 3(c)(v) in the evidence document.

A computer game requires users to travel around a world to find and open treasure chests. Each treasure chest has a mathematics question inside. The user enters the answer. The number of points awarded depends on the number of attempts before the user gives the correct answer. The program will be created using object-oriented programming (OOP). |The following class diagram describes the class TreasureChest.|| |---|---| |`TreasureChest`|`TreasureChest`| |`question : STRING`<br>`answer : INTEGER`<br>`points : INTEGER`|`// stores the question`<br>`// stores the answer`<br>`// stores the maximum possible number of`<br>`points available for this chest`| |`constructor()`<br>`getQuestion()`<br>`checkAnswer()`<br>`getPoints()`|<br>`// takes question, answer and points as`<br>`parameters and creates an instance of an`<br>`object`<br>`// returns the question`<br>`// takes the user’s answer as a parameter and`<br>`returns True if it is correct,`<br>`otherwise returns False`<br>`// takes the number of attempts as a`<br>`parameter and returns the number of`<br>`points awarded`| ### (a) Create a new program. <span class="part-marks">5 marks</span> Write program code to declare the class `TreasureChest` . Do **not** write any other methods. The attributes are private. If you are using the Python programming language, include attribute declarations using comments. Save your program as **question3** . Copy and paste the program code into **part 3(a)** in the evidence document. ### (b) The text file `TreasureChestData.txt` stores data for five questions, in the order of question, answer, points. <span class="part-marks">8 marks</span> For example, the first three lines of the file are for the first question: `2*2` question `4` answer `10` points Write program code for the procedure, `readData()` to: - read each question, answer and points from the text file - create an object of type `TreasureChest` for each question - declare an array named `arrayTreasure` of type `TreasureChest` - append each object to the array - use exception handling to output an appropriate message if the file is not found. Save your program. Copy and paste the program code into **part 3(b)** in the evidence document. ### (c) The main program repeats each question until the user inputs the correct answer. The number of points awarded depends on the number of attempts before the user gives the correct answer. #### (i) The class `TreasureChest` has a method `getQuestion()` that returns the question. <span class="part-marks">1 mark</span> Write the method `getQuestion()` . Save your program. Copy and paste the program code into **part 3(c)(i)** in the evidence document. #### (ii) The class `TreasureChest` has a method `checkAnswer()` that takes the user’s answer as a parameter. It returns `True` if the answer is correct and `False` otherwise. <span class="part-marks">3 marks</span> Write the method `checkAnswer()` . Save your program. Copy and paste the program code into **part 3(c)(ii)** in the evidence document. #### (iii) The class `TreasureChest` has a method `getPoints()` that takes the number of attempts as a parameter. <span class="part-marks">5 marks</span> - If the number of attempts is 1, it returns the value of `points` . - If the number of attempts is 2, it returns the integer value of `points` divided by 2 ( `DIV 2` ). - If the number of attempts is 3 or 4, it returns the integer value of `points` divided by 4 ( `DIV 4` ). - If the number of attempts is not 1 or 2 or 3 or 4, it returns `0` (zero). For example, a question is worth 100 points and the user took 2 attempts to give the correct answer. The user is awarded 50 points (100 DIV 2). Write the method `getPoints()` . Save your program. Copy and paste the program code into **part 3(c)(iii)** in the evidence document. #### (iv) Write program code for the main program to: <span class="part-marks">7 marks</span> - call the procedure `readData()` - ask the user to enter a question number between 1 and 5 - output the question that matches the question number entered by the user - check if the answer input by the user is correct using the method `checkAnswer()` - repeat the question until the user inputs the correct answer - count how many times the user attempted the question - use the method `getPoints()` to return the number of points awarded - output the number of points the user is awarded. Save your program. Copy and paste the program code into **part 3(c)(iv)** in the evidence document. #### (v) Test the program. <span class="part-marks">2 marks</span> Take a screenshot showing the input(s) and output(s) for each of the following two tests. In the first test: - select question 1 and answer it correctly the first time. In the second test: - select question 5 and answer it correctly the second time. Save your program. Copy and paste the screenshots into **part 3(c)(v)** in the evidence document.
Show mark scheme

3(a)

import java.util.Scanner; class treasureChest{ private String question; private Integer answer; private Integer points; public treasureChest(String questionP, Integer answerP, Integer pointsP){ question = questionP; answer = answerP; points = pointsP; }

3(b)

catch(FileNotFoundException ex){ System.out.println("No file found"); } catch(IOException ex){ System.out.println("No file found"); }

3(c)(i) [1 mark]

1 mark for returning the value of question Example code: Visual Basic Return question End Function Python return self.__question return question;

3(c)(ii) [3 marks]

1 mark per bullet point Comparing parameter to that object ’ s answer… …returning True if correct and False otherwise Example code: Visual Basic If answer = answerP Then Return True Else Return False End If End Function Python if int(self.__answer) == answerP: return True else: return False if (answer == answerP){ return true; }else{ return false; }

3(c)(iii)

public Integer getPoints(Integer attempts){ if (attempts == 1){ return points; }else if(attempts == 2){ return Math.round(points/2); }else if(attempts == 3 || attempts == 4){ return Math.round(points/4); }else{ return 0; }

3(c)(iv)

public static void main(String[] args){ readData(); Scanner scanner = new Scanner(System.in); System.out.println("Pick a treasure chest to open"); Integer answer; Integer choice; choice= Integer.parseInt(scanner.nextLine()); Integer attempts; if (choice> 0 && choice < 6){ Boolean result = false; attempts = 0; while (result == false){ answer = Integer.parseInt(scanner.nextLine()); attempts++; } System.out.println(arrayTreasure[choice-1].getPoints(attempts)); }

3(c)(v) [2 marks]

1 mark per screenshot Screenshot: outputting 2*2 entering 4 outputting 10 Screenshot: outputting 3000+4000 entering an incorrect value entering 7000 outputting 9

Q3
May/Jun 2021 Paper 4 v3

A computer game requires users to travel around a world to find and open treasure chests. Each treasure chest has a mathematics question inside. The user enters the answer. The number of points awarded depends on the number of attempts before the user gives the correct answer.

The program will be created using object-oriented programming (OOP).

The following class diagram describes the class TreasureChest.
TreasureChest TreasureChest
question : STRING
answer : INTEGER
points : INTEGER
// stores the question
// stores the answer
// stores the maximum possible number of
points available for this chest
constructor()
getQuestion()
checkAnswer()
getPoints()

// takes question, answer and points as
parameters and creates an instance of an
object
// returns the question
// takes the user’s answer as a parameter and
returns True if it is correct,
otherwise returns False
// takes the number of attempts as a
parameter and returns the number of
points awarded

(a) Create a new program. 5 marks

Write program code to declare the class TreasureChest .

Do not write any other methods.

The attributes are private.

If you are using the Python programming language, include attribute declarations using comments.

Save your program as question3 .

Copy and paste the program code into part 3(a) in the evidence document.

(b) The text file TreasureChestData.txt stores data for five questions, in the order of question, answer, points. 8 marks

For example, the first three lines of the file are for the first question:

2*2 question 4 answer 10 points

Write program code for the procedure, readData() to:

  • read each question, answer and points from the text file

  • create an object of type TreasureChest for each question

  • declare an array named arrayTreasure of type TreasureChest

  • append each object to the array

  • use exception handling to output an appropriate message if the file is not found.

Save your program.

Copy and paste the program code into part 3(b) in the evidence document.

(c) The main program repeats each question until the user inputs the correct answer. The number of points awarded depends on the number of attempts before the user gives the correct answer.

(i) The class TreasureChest has a method getQuestion() that returns the question. 1 mark

Write the method getQuestion() .

Save your program.

Copy and paste the program code into part 3(c)(i) in the evidence document.

(ii) The class TreasureChest has a method checkAnswer() that takes the user’s answer as a parameter. It returns True if the answer is correct and False otherwise. 3 marks

Write the method checkAnswer() .

Save your program.

Copy and paste the program code into part 3(c)(ii) in the evidence document.

(iii) The class TreasureChest has a method getPoints() that takes the number of attempts as a parameter. 5 marks

  • If the number of attempts is 1, it returns the value of points .

  • If the number of attempts is 2, it returns the integer value of points divided by 2 ( DIV 2 ).

  • If the number of attempts is 3 or 4, it returns the integer value of points divided by 4 ( DIV 4 ).

  • If the number of attempts is not 1 or 2 or 3 or 4, it returns 0 (zero).

For example, a question is worth 100 points and the user took 2 attempts to give the correct answer. The user is awarded 50 points (100 DIV 2).

Write the method getPoints() .

Save your program.

Copy and paste the program code into part 3(c)(iii) in the evidence document.

(iv) Write program code for the main program to: 7 marks

  • call the procedure readData()

  • ask the user to enter a question number between 1 and 5

  • output the question that matches the question number entered by the user

  • check if the answer input by the user is correct using the method checkAnswer()

  • repeat the question until the user inputs the correct answer

  • count how many times the user attempted the question

  • use the method getPoints() to return the number of points awarded

  • output the number of points the user is awarded.

Save your program.

Copy and paste the program code into part 3(c)(iv) in the evidence document.

(v) Test the program. 2 marks

Take a screenshot showing the input(s) and output(s) for each of the following two tests.

In the first test:

  • select question 1 and answer it correctly the first time.

In the second test:

  • select question 5 and answer it correctly the second time.

Save your program.

Copy and paste the screenshots into part 3(c)(v) in the evidence document.

A computer game requires users to travel around a world to find and open treasure chests. Each treasure chest has a mathematics question inside. The user enters the answer. The number of points awarded depends on the number of attempts before the user gives the correct answer. The program will be created using object-oriented programming (OOP). |The following class diagram describes the class TreasureChest.|| |---|---| |`TreasureChest`|`TreasureChest`| |`question : STRING`<br>`answer : INTEGER`<br>`points : INTEGER`|`// stores the question`<br>`// stores the answer`<br>`// stores the maximum possible number of`<br>`points available for this chest`| |`constructor()`<br>`getQuestion()`<br>`checkAnswer()`<br>`getPoints()`|<br>`// takes question, answer and points as`<br>`parameters and creates an instance of an`<br>`object`<br>`// returns the question`<br>`// takes the user’s answer as a parameter and`<br>`returns True if it is correct,`<br>`otherwise returns False`<br>`// takes the number of attempts as a`<br>`parameter and returns the number of`<br>`points awarded`| ### (a) Create a new program. <span class="part-marks">5 marks</span> Write program code to declare the class `TreasureChest` . Do **not** write any other methods. The attributes are private. If you are using the Python programming language, include attribute declarations using comments. Save your program as **question3** . Copy and paste the program code into **part 3(a)** in the evidence document. ### (b) The text file `TreasureChestData.txt` stores data for five questions, in the order of question, answer, points. <span class="part-marks">8 marks</span> For example, the first three lines of the file are for the first question: `2*2` question `4` answer `10` points Write program code for the procedure, `readData()` to: - read each question, answer and points from the text file - create an object of type `TreasureChest` for each question - declare an array named `arrayTreasure` of type `TreasureChest` - append each object to the array - use exception handling to output an appropriate message if the file is not found. Save your program. Copy and paste the program code into **part 3(b)** in the evidence document. ### (c) The main program repeats each question until the user inputs the correct answer. The number of points awarded depends on the number of attempts before the user gives the correct answer. #### (i) The class `TreasureChest` has a method `getQuestion()` that returns the question. <span class="part-marks">1 mark</span> Write the method `getQuestion()` . Save your program. Copy and paste the program code into **part 3(c)(i)** in the evidence document. #### (ii) The class `TreasureChest` has a method `checkAnswer()` that takes the user’s answer as a parameter. It returns `True` if the answer is correct and `False` otherwise. <span class="part-marks">3 marks</span> Write the method `checkAnswer()` . Save your program. Copy and paste the program code into **part 3(c)(ii)** in the evidence document. #### (iii) The class `TreasureChest` has a method `getPoints()` that takes the number of attempts as a parameter. <span class="part-marks">5 marks</span> - If the number of attempts is 1, it returns the value of `points` . - If the number of attempts is 2, it returns the integer value of `points` divided by 2 ( `DIV 2` ). - If the number of attempts is 3 or 4, it returns the integer value of `points` divided by 4 ( `DIV 4` ). - If the number of attempts is not 1 or 2 or 3 or 4, it returns `0` (zero). For example, a question is worth 100 points and the user took 2 attempts to give the correct answer. The user is awarded 50 points (100 DIV 2). Write the method `getPoints()` . Save your program. Copy and paste the program code into **part 3(c)(iii)** in the evidence document. #### (iv) Write program code for the main program to: <span class="part-marks">7 marks</span> - call the procedure `readData()` - ask the user to enter a question number between 1 and 5 - output the question that matches the question number entered by the user - check if the answer input by the user is correct using the method `checkAnswer()` - repeat the question until the user inputs the correct answer - count how many times the user attempted the question - use the method `getPoints()` to return the number of points awarded - output the number of points the user is awarded. Save your program. Copy and paste the program code into **part 3(c)(iv)** in the evidence document. #### (v) Test the program. <span class="part-marks">2 marks</span> Take a screenshot showing the input(s) and output(s) for each of the following two tests. In the first test: - select question 1 and answer it correctly the first time. In the second test: - select question 5 and answer it correctly the second time. Save your program. Copy and paste the screenshots into **part 3(c)(v)** in the evidence document.
Show mark scheme

3(a)

import java.util.Scanner; class treasureChest{ private String question; private Integer answer; private Integer points; public treasureChest(String questionP, Integer answerP, Integer pointsP){ question = questionP; answer = answerP; points = pointsP; }

3(b)

catch(FileNotFoundException ex){ System.out.println("No file found"); } catch(IOException ex){ System.out.println("No file found"); }

3(c)(i) [1 mark]

1 mark for returning the value of question Example code: Visual Basic Return question End Function Python return self.__question return question;

3(c)(ii) [3 marks]

1 mark per bullet point Comparing parameter to that object ’ s answer… …returning True if correct and False otherwise Example code: Visual Basic If answer = answerP Then Return True Else Return False End If End Function Python if int(self.__answer) == answerP: return True else: return False if (answer == answerP){ return true; }else{ return false; }

3(c)(iii)

public Integer getPoints(Integer attempts){ if (attempts == 1){ return points; }else if(attempts == 2){ return Math.round(points/2); }else if(attempts == 3 || attempts == 4){ return Math.round(points/4); }else{ return 0; }

3(c)(iv)

public static void main(String[] args){ readData(); Scanner scanner = new Scanner(System.in); System.out.println("Pick a treasure chest to open"); Integer answer; Integer choice; choice= Integer.parseInt(scanner.nextLine()); Integer attempts; if (choice> 0 && choice < 6){ Boolean result = false; attempts = 0; while (result == false){ answer = Integer.parseInt(scanner.nextLine()); attempts++; } System.out.println(arrayTreasure[choice-1].getPoints(attempts)); }

3(c)(v) [2 marks]

1 mark per screenshot Screenshot: outputting 2*2 entering 4 outputting 10 Screenshot: outputting 3000+4000 entering an incorrect value entering 7000 outputting 9