Skip to content

20.2 File Processing & Exception Handling

A Level · 50 questions found

  • Open (read/write/append) and close files in code
  • Read and write records to a file
  • File operations on serial, sequential and random files
  • What an exception is; when to use exception handling; write exception-handling code
Q10
Oct/Nov 2025 Paper 3 v1

Explain what is meant by exception handling. Include an example of a possible cause of an exception in your answer.

Explanation

Example 3 marks

Explain what is meant by exception handling. Include an example of a possible cause of an exception in your answer. Explanation Example <span class="part-marks">3 marks</span>
Show mark scheme

10 [3 marks]

One mark per mark point ( Max 2 ) MP1 Exception handling is a process that responds to unwanted / unexpected events when a program runs MP2 … to prevent the program / computer from stopping unexpectedly One mark for example ( Max 1 ) MP3 Programming errors MP4 User errors MP5 Hardware failure // losing connection to a device such as a printer

Q10
Oct/Nov 2025 Paper 3 v2

An exception is an error that may cause a program to halt unexpectedly.

(a) Describe how program termination due to an exception can be avoided. 2 marks

(b) Identify two possible causes of exceptions. 2 marks

1

2

An exception is an error that may cause a program to halt unexpectedly. ### (a) Describe how program termination due to an exception can be avoided. <span class="part-marks">2 marks</span> ### (b) Identify two possible causes of exceptions. <span class="part-marks">2 marks</span> 1 2
Show mark scheme

10(a) [2 marks]

One mark per mark point ( Max 2 ) MP1 Use an exception handling routine (to respond to unwanted / unexpected events when the program is running) MP2 Use of try … except / catch // Generate some form of error message

10(b) [2 marks]

One mark per mark point ( Max 2 ) MP1 Coding errors MP2 User errors MP3 Hardware failure // Losing connection to a device e.g. a printer

Q1
Oct/Nov 2025 Paper 4 v1

A program stores integers in a stack. The stack is represented as a 1D array of 30 elements with the identifier Stack

The global pointer TopOfStack stores the index of the last element inserted into the stack. TopOfStack is initialised to –1

(a) Write program code to declare Stack, initialise each element in the array with a null value and declare and initialise TopOfStack Save your program as Question1_N25 . 2 marks

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

(b) The function Push() takes an integer parameter. If the stack is full, the function returns FALSE . If the stack is not full, the parameter is inserted into the stack, the pointer is updated and the function returns TRUE Write the program code for Push() Save your program. 4 marks

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

A program stores integers in a stack. The stack is represented as a 1D array of 30 elements with the identifier `Stack` The global pointer `TopOfStack` stores the index of the last element inserted into the stack. `TopOfStack` is initialised to `–1` ### (a) Write program code to declare `Stack`, initialise each element in the array with a null value and declare and initialise `TopOfStack` Save your program as **Question1_N25** . <span class="part-marks">2 marks</span> Copy and paste the program code into part **1(a)** in the evidence document. ### (b) The function `Push()` takes an integer parameter. If the stack is full, the function returns `FALSE` . If the stack is not full, the parameter is inserted into the stack, the pointer is updated and the function returns `TRUE` Write the program code for `Push()` Save your program. <span class="part-marks">4 marks</span> Copy and paste the program code into part **1(b)** in the evidence document.
Show mark scheme

1(a) [2 marks]

1 mark each • (Global) 1D array initialised with 30 null values • (Global) initialised with TopofStack –1 Example program code Java public static Integer[] Stack = new Integer[30]; public static Integer TopOfStack; public static void main(String args[]){ for(Integer X = 0; X < 30; X++){ Stack[X] = null; } TopOfStack = -1; } VB.NET Dim Stack(29) As Integer Dim TopOfStack As Integer Sub Main(args As String()) For x = 0 To 29 Stack(x) = Nothing Next TopOfStack = -1 End Sub Python Stack = [None for x in range(30)] TopOfStack = -1

1(b)

Python def Push(DataToPush): global Stack global TopOfStack if TopOfStack < 29: TopOfStack = TopOfStack + 1 Stack[TopOfStack] = DataToPush return True else: return False

1(c)

Python def Pop(): global Stack global TopOfStack if TopOfStack == -1: return -999 else: DataReturn = Stack[TopOfStack] TopOfStack = TopOfStack - 1 return DataReturn

1(d) [4 marks]

1 mark each • Looping 40 times • Generating random number between 0 and 1000 inclusive inside the loop • Calling with each random number and storing/using return value … … if return value is Push() and breaking out of loop full Example program code Java for(Integer X = 0; X < 40; X++){ Pushed = Push(RandomNumber.nextInt(1001)); if(Pushed == false){ System.out.println("Stack full"); X = 40; } } VB.NET For x = 0 To 39 Pushed = Push(RandomNumber.Next(0, 1000)) If Pushed = False Then Console.WriteLine("Stack full") x = 40 End If Next Python for x in range(40): Pushed = Push(random.randint(0,1000)) if Pushed == False: print("Stack full") break

1(e)

VB.NET Sub FindValues() Dim Highest, Lowest As Integer Highest = Pop() Lowest = Highest Dim ReturnValue As Integer = Highest While ReturnValue <> -999 If ReturnValue > Highest Then Highest = ReturnValue End If If ReturnValue < Lowest Then Lowest = ReturnValue End If ReturnValue = Pop() End While Console.WriteLine("The highest value is " & Highest & " and the lowest value is " & Lowest) End Sub Python def FindValues(): Highest = Pop() Lowest = Highest ReturnValue = Lowest while(ReturnValue != -999): if ReturnValue > Highest: Highest = ReturnValue if ReturnValue < Lowest: Lowest = ReturnValue ReturnValue = Pop() print("The highest value is", Highest, "and the lowest value is", Lowest)

1(f)(i) [1 mark]

1 mark for calling FindValues() Example program code Java FindValues(); VB.NET FindValues() Python FindValues()

1(f)(ii) [1 mark]

1 mark for a screenshot of output showing Stack full output once Lowest value output in an appropriate message Highest value output in an appropriate message Lowest and Highest must be 0–1000 inclusive

Q3
Oct/Nov 2025 Paper 4 v1

A program stores records in the 2D array HashTable . Each record is stored at a specific index of the array that is calculated using a hashing algorithm with the record’s key field.

The array has 100 × 10 elements. The hashing algorithm uses the key to generate an index between 0 and 99 (inclusive). If two key fields generate the same index, there is a collision. Any records that have a collision are stored in the next space in the same index.

For example: In this table two record keys generated the same hash value of 1. Four record keys generated the same hash value of 3.

Index 0 1 2 3 4 5 9
0 record
1 record record
2
3 record record record record
4
99

The program uses Object-Oriented Programming (OOP).

(a) The class Record stores data about the records:
Record Record
Key : Integer
Data : String
stores the integer key field for the data
stores the string data

Constructor()
initialisesKey andData to its parameter values

The attributes Key and Data are public.

Write program code to declare the class Record and its constructor.

Use your programming language appropriate constructor.

Save your program as Question3_N25 .

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

(b) The procedure InitialiseHashTable() initialises each element in the array to an empty or null record. 2 marks

Write program code to declare the global 2D array HashTable and the procedure

    InitialiseHashTable()

Save your program.

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

(c) The function Hash() : 2 marks

  • takes an integer key field as a parameter

  • calculates and returns the hash value of the key field.

The hash value is the result from the formula: key MOD 100

Write program code for Hash()

Save your program.

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

(d) The procedure InsertData() : 4 marks

  • takes an object of type Record as a parameter

  • calculates the hash value for the parameter using the appropriate function

  • stores the parameter in the correct position in HashTable

You can assume there will be no more than 10 objects that generate the same hash value.

Write program code for InsertData()

Save your program.

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

(e) The file "HashTableData.txt" stores 200 key values and string data items in the format: 5 marks

        key,string

For example, the first row in the text file is:

        528,permission

The key is 528 and the string data is "permission"

The procedure ReadData() :

  • opens the text file and reads each line

  • splits each line into the key and data

  • calls InsertData() with an object containing each key and matching data.

Write program code for ReadData()

Save your program.

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

(f) The function GetRecord() : 5 marks

  • takes an integer key field as a parameter

  • calculates the hash value for the key field using the appropriate function

  • searches the hash table for the record with the matching key field

  • returns the data for the record if the record is found

  • returns "Not found" if the record is not found.

Write program code for GetRecord()

Save your program.

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

(g) The main program:

  • calls InitialiseHashTable() and ReadData()

  • takes five integer key fields as input from the user

  • calls GetRecord() with each input and outputs the return value.

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

Save your program.

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

(ii) Test your program with the following five inputs in the order given: 2 marks

528

1128

1828

1062

Take a screenshot of the output(s).

Save your program.

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

A program stores records in the 2D array `HashTable` . Each record is stored at a specific index of the array that is calculated using a hashing algorithm with the record’s key field. The array has 100 × 10 elements. The hashing algorithm uses the key to generate an index between 0 and 99 (inclusive). If two key fields generate the same index, there is a collision. Any records that have a collision are stored in the next space in the same index. For example: In this table two record keys generated the same hash value of 1. Four record keys generated the same hash value of 3. |Index|0|1|2|3|4|5|…|9| |---|---|---|---|---|---|---|---|---| |**0**|record|||||||| |**1**|record|record||||||| |**2**||||||||| |**3**|record|record|record|record||||| |**4**||||||||| |**…**||||||||| |**99**||||||||| The program uses Object-Oriented Programming (OOP). |(a) The class Record stores data about the records:|| |---|---| |**`Record`**|**`Record`**| |`Key : Integer`<br>`Data : String`|stores the integer key field for the data<br>stores the string data| |<br>`Constructor()`|initialises`Key` and`Data` to its parameter values| The attributes `Key` and `Data` are public. Write program code to declare the class `Record` and its constructor. Use your programming language appropriate constructor. Save your program as **Question3_N25** . Copy and paste the program code into part **3(a)** in the evidence document. <span class="part-marks">2 marks</span> ### (b) The procedure `InitialiseHashTable()` initialises each element in the array to an empty or null record. <span class="part-marks">2 marks</span> Write program code to declare the global 2D array `HashTable` and the procedure ``` InitialiseHashTable() ``` Save your program. Copy and paste the program code into part **3(b)** in the evidence document. ### (c) The function `Hash()` : <span class="part-marks">2 marks</span> - takes an integer key field as a parameter - calculates and returns the hash value of the key field. The hash value is the result from the formula: `key MOD 100` Write program code for `Hash()` Save your program. Copy and paste the program code into part **3(c)** in the evidence document. ### (d) The procedure `InsertData()` : <span class="part-marks">4 marks</span> - takes an object of type `Record` as a parameter - calculates the hash value for the parameter using the appropriate function - stores the parameter in the correct position in `HashTable` You can assume there will be no more than 10 objects that generate the same hash value. Write program code for `InsertData()` Save your program. Copy and paste the program code into part **3(d)** in the evidence document. ### (e) The file `"HashTableData.txt"` stores 200 key values and string data items in the format: <span class="part-marks">5 marks</span> ``` key,string ``` For example, the first row in the text file is: ``` 528,permission ``` The key is `528` and the string data is `"permission"` The procedure `ReadData()` : - opens the text file and reads each line - splits each line into the key and data - calls `InsertData()` with an object containing each key and matching data. Write program code for `ReadData()` Save your program. Copy and paste the program code into part **3(e)** in the evidence document. ### (f) The function `GetRecord()` : <span class="part-marks">5 marks</span> - takes an integer key field as a parameter - calculates the hash value for the key field using the appropriate function - searches the hash table for the record with the matching key field - returns the data for the record if the record is found - returns `"Not found"` if the record is not found. Write program code for `GetRecord()` Save your program. Copy and paste the program code into part **3(f)** in the evidence document. ### (g) The main program: - calls `InitialiseHashTable()` and `ReadData()` - takes **five** integer key fields as input from the user - calls `GetRecord()` with each input and outputs the return value. #### (i) Write program code for the main program. <span class="part-marks">3 marks</span> Save your program. Copy and paste the program code into part **3(g)(i)** in the evidence document. #### (ii) Test your program with the following **five** inputs in the order given: <span class="part-marks">2 marks</span> 528 1128 1828 1062 Take a screenshot of the output(s). Save your program. Copy and paste the screenshot(s) into part **3(g)(ii)** in the evidence document.
Show mark scheme

3(a) [2 marks]

1 mark each • Class header (and end) and constructor header (and end) in class • Constructor takes two parameters and stores each in attributes Example program code Java class Record{ public Integer Key; public String Data; public Record(Integer pKey, String pData){ Key = pKey; Data = pData; } } VB.NET Class Record Dim Key As Integer Dim Data As String Sub New(pKey, pData) Key = pKey Data = pData End Sub End Class Python class Record: def init(self, pKey, pData): self.Key = pKey #integer self.Data = pData #string

3(b) [2 marks]

1 mark each •  2D array of 100 10 elements of type Record • Procedure header (and end) and initialises each element in the 2D array to an empty/null InitialiseHashTable() record in procedure Example program code Java public static Record[][] HashTable = new Record[100][10]; public static void InitialiseHashTable(){ Record EmptyRecord = new Record(-1,"-1"); for(Integer X = 0; X < 100; X++){ for(Integer Y = 0; Y < 10; Y++){ HashTable[X][Y] = EmptyRecord; } } } VB.NET Dim HashTable(99, 9) As Record Sub InitialiseHashTable() Dim EmptyRecord As Record = New Record(-1, "") For X = 0 To 99 For Y = 0 To 9 HashTable(X, Y) = EmptyRecord Next Next End Sub Python HashTable = [] def InitialiseHashTable(): global HashTable HashTable = [[Record(-1,"")]*10 for i in range(100)]

3(c) [2 marks]

1 mark each • Function header (and end) taking one parameter and returning calculated hash • …. hash calculated correctly from parameter Example program code Java public static Integer Hash(Integer TheKey){ return(TheKey % 100); } VB.NET Function Hash(Key) Return Key Mod 100 End Function Python def Hash(Key): return Key % 100

3(d)

Python def InsertData(RecordData): global HashTable HashValue = Hash(RecordData.Key) for X in range(0, 10): if HashTable[HashValue][X].Key == -1: HashTable[HashValue][X] = RecordData

3(e)

VB.NET Sub ReadData() Dim Line As String Dim Data(3) As String Dim TheRecord As Record Dim FileReader As New System.IO.StreamReader("HashTableData.txt") While Not FileReader.EndOfStream Line = FileReader.ReadLine() Data = Split(Line, ",") TheRecord = New Record(Integer.Parse(Data(0)), Data(1)) InsertData(TheRecord) End While FileReader.Close() End Sub Python def ReadData(): global HashTable File = open("HashTableData.txt") for Line in File: Data = Line.strip() Data = Line.split(",") InsertData(Record(int(Data[0]), Data[1])) File.close()

3(f)

Python def GetRecord(Key): global HashTable HashValue = Hash(Key) for X in range(0, 10): if HashTable[HashValue][X].Key == Key: return HashTable[HashValue][X].Data return "Not found"

3(g)(i)

Python InitialiseHashTable() ReadData() for x in range(5): Key = int(input("Enter key field ")) print(GetRecord(Key))

3(g)(ii) [2 marks]

1 mark each for screenshot(s) showing • Input of the 4 integers and matching word output 528 permission 1128 peace 1828 precedent 1062 up • Input of and output of 39 Not found e.g.

Q2
Oct/Nov 2025 Paper 4 v2

A program stores 20 unique random integers between 0 and 100 (inclusive) in a 1D array that is local to the main program.

(a) Write program code to declare the array local to the main program and store 20 unique random numbers between 0 and 100 (inclusive) in the array. 3 marks

Save your program as Question2_N25 .

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

(b) The procedure PrintArray() takes an integer array as a parameter. The procedure outputs the array contents on a single line with a space between each integer. 3 marks

Write the program code for PrintArray()

Save your program.

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

(c) The function BubbleSort() : 5 marks

  • takes an integer array as a parameter

  • sorts the data into ascending order using a bubble sort

  • returns the sorted array.

The function needs to work for an array of any length.

Do not use an inbuilt sorting method.

Write program code for BubbleSort()

Save your program.

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

  • outputs the contents of the array using PrintArray()

  • sorts the array using BubbleSort()

  • outputs "Sorted"

  • outputs the contents of the sorted array using PrintArray()

Write program code for the main program.

Save your program.

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

(ii) Test your program. 3 marks

Take a screenshot of the output(s).

Save your program.

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

(e) The recursive function RecursiveBinarySearch() takes four parameters: 1 mark 6 marks

  • an integer array

  • the lower bound of the array

  • the upper bound of the array

  • the value to find in the array.

The recursive function performs a binary search to find the index of the value in the array. The function returns the index of the value if it is found. The function returns –1 if the value is not found.

Write program code for RecursiveBinarySearch()

Save your program.

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

(f) (i) The main program: 3 marks

  • prompts the user to enter an integer

  • takes the integer as input

  • calls RecursiveBinarySearch() with the sorted array, appropriate lower bound, appropriate upper bound and the user’s input as parameters

  • outputs "Not found" if the input is not within the array

  • outputs "Found at position" and the index if the input is within the array.

Write program code to amend the main program.

Save your program.

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

(ii) Test your program three times with each of the inputs described: 2 marks

Test 1: the smallest number in the array

Test 2: the largest number in the array

Test 3: a number not in the array

Take a screenshot of each output.

Save your program.

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

A program stores 20 unique random integers between 0 and 100 (inclusive) in a 1D array that is local to the main program. ### (a) Write program code to declare the array local to the main program and store 20 **unique** random numbers between 0 and 100 (inclusive) in the array. <span class="part-marks">3 marks</span> Save your program as **Question2_N25** . Copy and paste the program code into part **2(a)** in the evidence document. ### (b) The procedure `PrintArray()` takes an integer array as a parameter. The procedure outputs the array contents on a single line with a space between each integer. <span class="part-marks">3 marks</span> Write the program code for `PrintArray()` Save your program. Copy and paste the program code into part **2(b)** in the evidence document. ### (c) The function `BubbleSort()` : <span class="part-marks">5 marks</span> - takes an integer array as a parameter - sorts the data into ascending order using a bubble sort - returns the sorted array. The function needs to work for an array of any length. Do **not** use an inbuilt sorting method. Write program code for `BubbleSort()` Save your program. Copy and paste the program code into part **2(c)** in the evidence document. **(d) (i)** The main program: - outputs the contents of the array using `PrintArray()` - sorts the array using `BubbleSort()` - outputs `"Sorted"` - outputs the contents of the sorted array using `PrintArray()` Write program code for the main program. 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">3 marks</span> Take a screenshot of the output(s). Save your program. Copy and paste the screenshot(s) into part **2(d)(ii)** in the evidence document. ### (e) The recursive function `RecursiveBinarySearch()` takes four parameters: <span class="part-marks">1 mark</span> <span class="part-marks">6 marks</span> - an integer array - the lower bound of the array - the upper bound of the array - the value to find in the array. The recursive function performs a binary search to find the index of the value in the array. The function returns the index of the value if it is found. The function returns `–1` if the value is not found. Write program code for `RecursiveBinarySearch()` Save your program. Copy and paste the program code into part **2(e)** in the evidence document. ### (f) **(i)** The main program: <span class="part-marks">3 marks</span> - prompts the user to enter an integer - takes the integer as input - calls `RecursiveBinarySearch()` with the sorted array, appropriate lower bound, appropriate upper bound and the user’s input as parameters - outputs `"Not found"` if the input is not within the array - outputs `"Found at position"` and the index if the input is within the array. Write program code to amend the main program. Save your program. Copy and paste the program code into part **2(f)(i)** in the evidence document. #### (ii) Test your program **three** times with each of the inputs described: <span class="part-marks">2 marks</span> Test 1: the smallest number in the array Test 2: the largest number in the array Test 3: a number **not** in the array Take a screenshot of each output. Save your program. Copy and paste the screenshot(s) into part **2(f)(ii)** in the evidence document.
Show mark scheme

2(a)

Python TheArray = [] TheArray = random.sample(range(0,101),20)

2(b) [3 marks]

1 mark each • Procedure header (and close) taking (array) as parameter • Outputting array contents once … • … on one line with a space between each integer Example program code Java public static void PrintArray(Integer[] DataArray){ String Output = ""; for(Integer X = 0; X < 20; X++){ Output += Integer.toString(DataArray[X]) + " "; } System.out.println(Output); } VB.NET Sub PrintArray(DataArray() As Integer) Dim Output As String = "" For X = 0 To 19 Output = Output + Str(DataArray(X)) + " " Next X Console.WriteLine(Output) End Sub Python def PrintArray(DataArray): Output = "" for Item in DataArray: Output = Output + str(Item) + " " print(Output)

2(c)

VB.NET Function BubbleSort(DataArray() As Integer) Dim Swap As Boolean = True Dim Temp As Integer While Swap = True Swap = False For X = 0 To DataArray.Length - 2 If DataArray(X) > DataArray(X + 1) Then Temp = DataArray(X) DataArray(X) = DataArray(X + 1) DataArray(X + 1) = Temp Swap = True End If Next X End While Return DataArray End Function Python def BubbleSort(DataArray): Swap = True while Swap == True: Swap = False for y in range(0, len(DataArray)-1): if DataArray[y] > DataArray[y+1]: DataArray[y], DataArray[y+1] = DataArray[y+1], DataArray[y] Swap = True return DataArray

2(d)(i) [3 marks]

1 mark each • Calling with array as argument PrintArray() • Calling with array as argument and storing/using return value BubbleSort() • Outputting and calling with (returned) array as argument "Sorted" PrintArray() Example program code Java PrintArray(TheArray); Integer[] SortedArray = new Integer[20]; SortedArray = BubbleSort(TheArray); System.out.println("Sorted"); PrintArray(SortedArray); VB.NET PrintArray(TheArray) Dim SortedArray(19) As Integer SortedArray = BubbleSort(TheArray) Console.WriteLine("Sorted") PrintArray(SortedArray) Python PrintArray(TheArray) SortedArray = BubbleSort(TheArray) print("Sorted") PrintArray(SortedArray)

2(d)(ii) [1 mark]

1 mark • Output shows unsorted array of 20 integers between 0 and 100 inclusive before sorting, “Sorted” output, array of the same integers sorting into ascending order. All screenshots will be unique to the candidate

2(e)

VB.NET Function RecursiveBinarySearch(DataArray() As Integer, Lower As Integer, Upper As Integer, DataToFind As Integer) Dim Middle As Integer If Upper >= Lower Then Middle = Lower + (Upper - Lower) \ 2 If DataArray(Middle) = DataToFind Then Return Middle ElseIf DataArray(Middle) > DataToFind Then Return RecursiveBinarySearch(DataArray, Lower, Middle - 1, DataToFind) Else Return RecursiveBinarySearch(DataArray, Middle + 1, Upper, DataToFind) End If Else Return -1 End If End Function Python def RecursiveBinarySearch(DataArray, Lower, Upper, DataToFind): if Upper >= Lower: Middle = Lower + (Upper - Lower) // 2 if DataArray[Middle] == DataToFind: return Middle elif DataArray[Middle] > DataToFind: return RecursiveBinarySearch(DataArray, Lower, Middle - 1, DataToFind) else: return RecursiveBinarySearch(DataArray, Middle + 1, Upper, DataToFind) else: return -1

2(f)(i) [3 marks]

1 mark each • Prompt and input of integer • Call of RecursiveBinarySearch(SortedArray, 0, 19, input) • Output of if returned and output "Not found" –1 "Found at position" Example program code Java System.out.println("Enter the number to find"); Scanner scanner = new Scanner(System.in); Integer DataToFind = Integer.parseInt(scanner.nextLine()); Integer Location = RecursiveBinarySearch(SortedArray, 0, 19, DataToFind); if(Location == -1){ System.out.println("Not found"); }else{ System.out.println("Found at position " + Location); } VB.NET Console.WriteLine("Enter the number to find ") Dim DataToFind As Integer = Console.ReadLine() Dim Location As Integer = RecursiveBinarySearch(SortedArray, 0, 19, DataToFind) If Location = -1 Then Console.WriteLine("Not found") Else Console.WriteLine("Found at position " & Location) End If Python DataToFind = int(input("Enter the number to find ")) Location = RecursiveBinarySearch(SortedArray, 0, 19, DataToFind) if Location == -1: print("Not found") else: print("Found at position", Location)

2(f)(ii) [2 marks]

1 mark each • screenshot showing smallest number in array input and found message with index 0 number in array input and found message with index 19 • screenshot showing a number not in the array input and an output of "Not found" All screenshots will be unique to the candidate

Q3
Oct/Nov 2025 Paper 4 v2

A program stores integers in ascending order in an ordered binary tree. The tree is implemented as a 2D array.

Each node is stored with three values:

  • a pointer to the left node

  • the data

  • a pointer to the right node.

All null values are stored as –1

The binary tree can store up to 50 nodes.

Nodes cannot be deleted from the binary tree.

(a) The binary tree is stored as a global array with the identifier TreeArray . The left pointer, the data and the right pointer of each node are initialised to –1 The global variable RootPointer stores the index of the root node in the tree, initialised to 3 marks

    –1

The global variable FreeNode stores the index of the next free node in the array, initialised to 0

Write program code to declare and initialise TreeArray, RootPointer and FreeNode

Save your program as Question3_N25 .

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

(b) The procedure AddNode() : 7 marks

  • takes an integer to store in the binary tree as a parameter

  • stores the parameter in the next free node in the array

  • finds the position to store the data in the tree by following the appropriate pointers

  • updates the pointer of the new node’s parent node.

The procedure outputs "The tree is full" if the parameter cannot be stored because the tree is full.

Write program code for AddNode()

Save your program.

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

(c) The text file TreeData.txt stores 50 integers. Each integer is on a new line in the file. 4 marks

The main program reads each integer from the file and stores each integer in the binary tree in the order they are read.

Write program code for the main program.

Save your program.

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

(d) The procedure WriteAllToFile() stores the content of TreeArray in a new text file with the filename Tree.txt . The file Tree.txt is not provided. 5 marks

Each node in TreeArray is stored on one line with a comma separating each value.

For example, the current contents of TreeArray are:

Index 0 1 2
0 –1 20 1
1 –1 30 –1
49 -1 -1 -1

After writing TreeArray to the text file, Tree.txt will contain:

    –1,20,1
    –1,30,–1

    -1,-1,-1

Write program code for WriteAllToFile()

Include exception handling when writing to the file.

Save your program.

Copy and paste the program code into part 3(d) in the evidence document. (e) (i) Amend the main program to call WriteAllToFile() 1 mark

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 that shows all of the content stored in the file Tree.txt

In this screenshot you need to make sure the filename is visible.

Save your program.

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

A program stores integers in ascending order in an ordered binary tree. The tree is implemented as a 2D array. Each node is stored with three values: - a pointer to the left node - the data - a pointer to the right node. All null values are stored as `–1` The binary tree can store up to 50 nodes. Nodes cannot be deleted from the binary tree. ### (a) The binary tree is stored as a global array with the identifier `TreeArray` . The left pointer, the data and the right pointer of each node are initialised to `–1` The global variable `RootPointer` stores the index of the root node in the tree, initialised to <span class="part-marks">3 marks</span> ``` –1 ``` The global variable `FreeNode` stores the index of the next free node in the array, initialised to `0` Write program code to declare and initialise `TreeArray`, `RootPointer` and `FreeNode` Save your program as **Question3_N25** . Copy and paste the program code into part **3(a)** in the evidence document. ### (b) The procedure `AddNode()` : <span class="part-marks">7 marks</span> - takes an integer to store in the binary tree as a parameter - stores the parameter in the next free node in the array - finds the position to store the data in the tree by following the appropriate pointers - updates the pointer of the new node’s parent node. The procedure outputs `"The tree is full"` if the parameter cannot be stored because the tree is full. Write program code for `AddNode()` Save your program. Copy and paste the program code into part **3(b)** in the evidence document. ### (c) The text file `TreeData.txt` stores 50 integers. Each integer is on a new line in the file. <span class="part-marks">4 marks</span> The main program reads each integer from the file and stores each integer in the binary tree in the order they are read. Write program code for the main program. Save your program. Copy and paste the program code into part **3(c)** in the evidence document. ### (d) The procedure `WriteAllToFile()` stores the content of `TreeArray` in a new text file with the filename `Tree.txt` . The file `Tree.txt` is not provided. <span class="part-marks">5 marks</span> Each node in `TreeArray` is stored on one line with a comma separating each value. For example, the current contents of `TreeArray` are: |Index|0|1|2| |---|---|---|---| |**`0`**|`–1`|`20`|` 1`| |**`1`**|`–1`|`30`|`–1`| |…|||| |**`49`**|`-1`|`-1`|`-1`| After writing `TreeArray` to the text file, `Tree.txt` will contain: ``` –1,20,1 –1,30,–1 ``` … ``` -1,-1,-1 ``` Write program code for `WriteAllToFile()` Include exception handling when writing to the file. Save your program. Copy and paste the program code into part **3(d)** in the evidence document. **(e) (i)** Amend the main program to call `WriteAllToFile()` <span class="part-marks">1 mark</span> 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 that shows all of the content stored in the file `Tree.txt` In this screenshot you need to make sure the filename is visible. Save your program. Copy and paste the screenshot(s) into part **3(e)(ii)** in the evidence document.
Show mark scheme

3(a)

Python TreeArray = [] for x in range(50): TreeArray.append([-1,-1,-1]) RootPointer = -1 FreeNode = 0

3(b)

if TreeArray[CurrentNode][0] == -1: TreeArray[CurrentNode][0] = FreeNode Placed = True else: CurrentNode = TreeArray[CurrentNode][0] else: if TreeArray[CurrentNode][2] == -1: TreeArray[CurrentNode][2] = FreeNode Placed = True else: CurrentNode = TreeArray[CurrentNode][2] FreeNode = FreeNode + 1 else: print("The tree is full")

3(c)

VB.NET Try Dim FileReader As New System.IO.StreamReader("TreeData.txt") While Not FileReader.EndOfStream AddNode(FileReader.ReadLine()) End While FileReader.Close() Catch ex As Exception Console.WriteLine("Cannot open file") End Try Python try: File= open("TreeData.txt") for Line in File: AddNode(int(Line.strip())) File.close() except: print("Error cannot open file")

3(d)

VB.NET Sub WriteAllToFile() Dim FileWriter As IO.StreamWriter = New IO.StreamWriter("Tree.txt", False) Dim Line As String Try For x = 0 To 49 Line = TreeArray(x, 0) & "," & TreeArray(x, 1) & "," & TreeArray(x, 2) FileWriter.WriteLine(Line) Next FileWriter.Close() Catch ex As Exception Console.WriteLine("Cannot open or write to file") End Try End Sub Python def WriteAllToFile(): try: File = open("Tree.txt","a+") for x in range(0, 50): Line = str(TreeArray[x][0]) + "," + str(TreeArray[x][1])+ "," + str(TreeArray[x][2]) + "\n" File.write(Line) File.close() except: print("Cannot write to file")

3(e)(i) [1 mark]

1 mark for calling WriteAllToFile() Example program code Java WriteAllToFile(); VB.NET WriteAllToFile() Python WriteAllToFile()

3(e)(ii) [1 mark]

1 mark for a screenshot that shows correct data stored, each node on a new line (in correct format). The screenshot must include the filename. e.g.

Q2
Oct/Nov 2025 Paper 4 v3

A program reads string data from a text file into a linear queue and then compresses the data.

The queue is created using the global 1D array Queue . The queue can store up to 100 elements. Each element is initialised to the empty string ""

The queue has two pointers that are global to the program:

  • QueueHead that points to the index of the first element in the queue, initialised to –1

  • QueueTail that points to the index of the last element in the queue, initialised to –1

The global variable NumberItems stores the number of elements stored in the queue, initialised to 0

(a) Write program code to declare and initialise Queue, QueueHead, QueueTail and 2 marks

    NumberItems

Save your program as Question2_N25 .

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

(b) The function Enqueue() takes a string as a parameter. The function checks if the queue is full, and returns Boolean FALSE if the queue is full. 5 marks

If the queue is not full, the parameter is inserted into the next position in Queue . The function updates the appropriate pointer(s), updates NumberItems and then returns Boolean TRUE

Write program code for Enqueue()

Save your program.

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

(c) The function Dequeue() returns the string "False" if the queue is empty. 3 marks

If the queue is not empty, the function returns the next element in the queue. The function updates the appropriate pointer(s) and updates NumberItems

Write program code for Dequeue()

Save your program.

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

(d) The text file BinaryData.txt stores individual binary digits, '1' and '0' . Each digit is on a new line. For example, the first line in the text file stores '1', the second line stores '1' The procedure ReadData() reads in each line from the text file BinaryData.txt and inserts it into the queue using the appropriate method. 5 marks

The procedure needs to work for a text file with any number of lines up to a maximum of 100.

Write program code for ReadData()

Save your program.

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

(e) The string data in the text file is compressed. 6 marks

The compression algorithm counts the number of times each binary digit appears consecutively, then stores the binary digit followed by the number of times it appears. The algorithm stores the compressed data in a single string.

For example, if the text file contains the data:

      1
      1
      0
      0
      0
      1
      1
      1

The compression algorithm will create the string "120313" because there are two '1' digits, followed by three '0' digits, followed by three '1' digits.

The procedure Compress() uses Dequeue() to remove each element from the queue in turn. The procedure then compresses the data following the compression algorithm described. The new compressed string is stored in the global variable NewString

You can assume that one binary digit will never appear more than nine times consecutively in the sequence.

You can assume that there will always be at least one item in the queue.

Write program code for Compress()

Save your program.

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

(f) (i) Write program code for the main program to: 2 marks

  • call ReadData()

  • call Compress()

  • output the content of the compressed string.

Save your program.

Copy and paste the program code into part 2(f)(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(s) into part 2(f)(ii) in the evidence document.

A program reads string data from a text file into a linear queue and then compresses the data. The queue is created using the global 1D array `Queue` . The queue can store up to 100 elements. Each element is initialised to the empty string `""` The queue has two pointers that are global to the program: - `QueueHead` that points to the index of the first element in the queue, initialised to `–1` - `QueueTail` that points to the index of the last element in the queue, initialised to `–1` The global variable `NumberItems` stores the number of elements stored in the queue, initialised to `0` ### (a) Write program code to declare and initialise `Queue`, `QueueHead`, `QueueTail` and <span class="part-marks">2 marks</span> ``` NumberItems ``` Save your program as **Question2_N25** . Copy and paste the program code into part **2(a)** in the evidence document. ### (b) The function `Enqueue()` takes a string as a parameter. The function checks if the queue is full, and returns Boolean `FALSE` if the queue is full. <span class="part-marks">5 marks</span> If the queue is not full, the parameter is inserted into the next position in `Queue` . The function updates the appropriate pointer(s), updates `NumberItems` and then returns Boolean `TRUE` Write program code for `Enqueue()` Save your program. Copy and paste the program code into part **2(b)** in the evidence document. ### (c) The function `Dequeue()` returns the string `"False"` if the queue is empty. <span class="part-marks">3 marks</span> If the queue is not empty, the function returns the next element in the queue. The function updates the appropriate pointer(s) and updates `NumberItems` Write program code for `Dequeue()` Save your program. Copy and paste the program code into part **2(c)** in the evidence document. ### (d) The text file `BinaryData.txt` stores individual binary digits, `'1'` and `'0'` . Each digit is on a new line. For example, the first line in the text file stores `'1'`, the second line stores `'1'` The procedure `ReadData()` reads in each line from the text file `BinaryData.txt` and inserts it into the queue using the appropriate method. <span class="part-marks">5 marks</span> The procedure needs to work for a text file with any number of lines up to a maximum of 100. Write program code for `ReadData()` Save your program. Copy and paste the program code into part **2(d)** in the evidence document. ### (e) The string data in the text file is compressed. <span class="part-marks">6 marks</span> The compression algorithm counts the number of times each binary digit appears consecutively, then stores the binary digit followed by the number of times it appears. The algorithm stores the compressed data in a single string. For example, if the text file contains the data: ``` 1 1 0 0 0 1 1 1 ``` The compression algorithm will create the string `"120313"` because there are two `'1'` digits, followed by three `'0'` digits, followed by three `'1'` digits. The procedure `Compress()` uses `Dequeue()` to remove each element from the queue in turn. The procedure then compresses the data following the compression algorithm described. The new compressed string is stored in the global variable `NewString` You can assume that one binary digit will never appear more than nine times consecutively in the sequence. You can assume that there will always be at least one item in the queue. Write program code for `Compress()` Save your program. Copy and paste the program code into part **2(e)** in the evidence document. ### (f) **(i)** Write program code for the main program to: <span class="part-marks">2 marks</span> - call `ReadData()` - call `Compress()` - output the content of the compressed string. Save your program. Copy and paste the program code into part **2(f)(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(s) into part **2(f)(ii)** in the evidence document.
Show mark scheme

2(a)

Python global Queue, QueueHead, QueueTail, NumberItems Queue = [] for x in range(100): Queue.append("") QueueHead = -1 QueueTail = -1 NumberItems = 0

2(b)

VB.NET Function Enqueue(TheData) If QueueHead = -1 Then Queue(0) = TheData QueueHead = 0 QueueTail = 0 NumberItems += 1 Return True ElseIf QueueTail >= 99 Then Queue(QueueTail + 1) = TheData QueueTail += 1 NumberItems += 1 Return True Else Return False End If End Function Python def Enqueue(TheData): global Queue, QueueHead, QueueTail, NumberItems if(QueueHead == -1){ Queue[0] = TheData QueueHead = 0 QueueTail = 0 NumberItems +=1 return True elif QueueTail >= 99: Queue[QueueTail+1] = TheData QueueTail +=1 NumberItems +=1 return True else: return False

2(c)

Python def Dequeue(): global Queue, QueueHead, QueueTail, NumberItems if NumberItems == 0: return "False" else: ReturnData = Queue[QueueHead] QueueHead += 1 NumberItems -=1 return ReturnData

2(d)

VB.NET Sub ReadData() Dim ReturnValue As String Dim DataReader As New System.IO.StreamReader("BinaryData.txt") Dim FinishLoop As Boolean = True Do Until DataReader.EndOfStream Or FinishLoop = False ReturnValue = Enqueue(DataReader.ReadLine()) If ReturnValue = False Then FinishLoop = False End If Loop DataReader.Close() End Sub Python def ReadData(): TheFile = open("BinaryData.txt") for Line in TheFile: ReturnValue = Enqueue(Line.strip()) if ReturnValue == False: break TheFile.close()

2(e)

VB.NET Sub Compress() Dim First As String = Dequeue() Dim NewLine As String = "" Dim Count As Integer Dim NextChar As String While NumberItems > 0 And First <> "False" Count = 1 NextChar = Dequeue() While NextChar = First Count += 1 First = NextChar NextChar = Dequeue() End While NewLine = First & Count NewString = NewString & NewLine First = NextChar End While Python def Compress(): global NewString First = Dequeue() NewString = "" while NumberItems > 0 and First != "False": Count = 1 NextChar = Dequeue() while NextChar == First: Count += 1 First = NextChar NextChar = Dequeue() NewLine = First + str(Count) NewString = NewString + NewLine First = NextChar

2(f)(i)

Python NewString = "" Queue = [] for x in range(100): Queue.append("") QueueHead = -1 QueueTail = -1 NumberItems = 0 ReadData() Compress() print(NewString)

2(f)(ii) [1 mark]

1 mark for screenshot showing output Example

Q3
Oct/Nov 2025 Paper 4 v3

A program is written to perform different individual processes using arrays.

(a) A 1D array stores 10 integers.

(i) A recursive function RecursiveCount() takes three parameters: 6 marks

  • ArrayCopy, an array of integers

  • NumberElements, the number of elements in the array of integers

  • DataToFind, an integer data to find in the array.

The function counts and returns the number of times DataToFind is in ArrayCopy

The recursive algorithm:

  • returns 0 if there are no elements in ArrayCopy

  • compares the first element in ArrayCopy with DataToFind

  • if the element matches, the function returns 1 added to the return value from a recursive call (passing the array without the first element)

  • if the element does not match, the function returns the return value from a recursive call (passing the array without the first element).

Write program code for RecursiveCount()

Save your program as Question3_N25 .

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

(ii) The main program stores the following data in a 1D array of integers in the order given: 3 marks

      0 5 1 2 5 9 9 6 5 0

The main program calls RecursiveCount() with the parameters:

  • 0 as the data to find

  • 10 as the number of elements

  • the array of 10 integers.

The return value is output.

Write program code for the main program.

Save your program.

Copy and paste the program code into part 3(a)(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(s) into part 3(a)(iii) in the evidence document.

(b) The program stores the following string. The string has four statements that are each terminated by a semi-colon ';'

    "x=0;y=1;x=x+y;y++;"

(i) Write program code to amend the main program to store the string "x=0;y=1;x=x+y;y++;" in a local variable. 1 mark

Save your program.

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

(ii) The function SplitData() splits a string parameter into four individual lines of code. 6 marks

The function creates an array of the strings where each line is stored in a new array element without the semi-colon.

The function returns the array of strings.

Do not use an inbuilt function to split the string.

Write program code for SplitData()

Save your program.

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

(iii) The main program needs to call SplitData() with the string from part 3(b)(i) . The main program then needs to output each element from the returned array on a new line. 2 marks

Write program code to amend the main program.

Save your program.

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

(iv) Test your program. 1 mark

Take a screenshot of the output(s).

Save your program.

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

A program is written to perform different individual processes using arrays. ### (a) A 1D array stores 10 integers. #### (i) A recursive function `RecursiveCount()` takes three parameters: <span class="part-marks">6 marks</span> - `ArrayCopy`, an array of integers - `NumberElements`, the number of elements in the array of integers - `DataToFind`, an integer data to find in the array. The function counts and returns the number of times `DataToFind` is in `ArrayCopy` The recursive algorithm: - returns `0` if there are no elements in `ArrayCopy` - compares the first element in `ArrayCopy` with `DataToFind` - if the element matches, the function returns `1` added to the return value from a recursive call (passing the array without the first element) - if the element does **not** match, the function returns the return value from a recursive call (passing the array without the first element). Write program code for `RecursiveCount()` Save your program as **Question3_N25** . Copy and paste the program code into part **3(a)(i)** in the evidence document. #### (ii) The main program stores the following data in a 1D array of integers in the order given: <span class="part-marks">3 marks</span> ``` 0 5 1 2 5 9 9 6 5 0 ``` The main program calls `RecursiveCount()` with the parameters: - `0` as the data to find - `10` as the number of elements - the array of 10 integers. The return value is output. Write program code for the main program. Save your program. Copy and paste the program code into part **3(a)(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(s) into part **3(a)(iii)** in the evidence document. ### (b) The program stores the following string. The string has four statements that are each terminated by a semi-colon `';'` ``` "x=0;y=1;x=x+y;y++;" ``` #### (i) Write program code to amend the main program to store the string `"x=0;y=1;x=x+y;y++;"` in a local variable. <span class="part-marks">1 mark</span> Save your program. Copy and paste the program code into part **3(b)(i)** in the evidence document. #### (ii) The function `SplitData()` splits a string parameter into **four** individual lines of code. <span class="part-marks">6 marks</span> The function creates an array of the strings where each line is stored in a new array element without the semi-colon. The function returns the array of strings. Do **not** use an inbuilt function to split the string. Write program code for `SplitData()` Save your program. Copy and paste the program code into part **3(b)(ii)** in the evidence document. #### (iii) The main program needs to call `SplitData()` with the string from part **3(b)(i)** . The main program then needs to output each element from the returned array on a new line. <span class="part-marks">2 marks</span> Write program code to amend the main program. Save your program. Copy and paste the program code into part **3(b)(iii)** in the evidence document. #### (iv) 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(s) into part **3(b)(iv)** in the evidence document.
Show mark scheme

3(a)(i)

VB.NET Function RecursiveCount(DataToFind As Integer, ArrayCopy() As Integer, NumberElements As Integer) If NumberElements > 0 Then Dim NewArray(NumberElements - 1) As Integer For x = 1 To NumberElements - 1 NewArray(x - 1) = ArrayCopy(x) Next x If ArrayCopy(0) = DataToFind Then Return 1 + RecursiveCount(DataToFind, NewArray, NumberElements - 1) Else Return RecursiveCount(DataToFind, NewArray, NumberElements - 1) End If Else Return 0 End If End Function Python def RecursiveCount(DataToFind, ArrayCopy, NumberElements): if NumberElements > 0: NewArray = ArrayCopy[1:] if ArrayCopy[0] == DataToFind: return 1 + RecursiveCount(DataToFind, NewArray, NumberElements - 1) else: return RecursiveCount(DataToFind, NewArray, NumberElements - 1) else: return 0

3(a)(ii) [3 marks]

1 mark each • Storing the correct data in an array • Calling with the correct parameters RecursiveCount() • Outputting the return value Example program code Java Integer[] MyArray = new Integer[]{0, 5, 1, 2, 5, 9, 9, 6, 5, 0}; System.out.println(RecursiveCount(0, MyArray, 10)); VB.NET Dim MyArray() As Integer = {0, 5, 1, 2, 5, 9, 9, 6, 5, 0} Console.WriteLine(RecursiveCount(0, MyArray, 10)) Python MyArray = [0,5,1,2,5,9,9,6,5,0] print(RecursiveCount(0, MyArray, 10))

3(a)(iii) [1 mark]

1 mark for screenshot showing correct output of 2 Example

3(b)(i) [1 mark]

1 mark for storing the string in a variable Example program code Java String Code = "x=0;y=1;x=x+y;y++;"; VB.NET Dim Code As String = "x=0;y=1;x=x+y;y++;" Python Code = "x=0;y=1;x=x+y;y++;"

3(b)(ii)

Python def SplitData(DataString): SplitDataArray = [] Count = 0 for x in range(4): TempString = "" try: Character = DataString[Count] while Character != ";": TempString = TempString + (Character) Count += 1 Character = DataString[Count] SplitDataArray.append(TempString) except: print("No more characters") Count += 1 return SplitDataArray

3(b)(iii) [2 marks]

1 mark each • Calling with array as argument and storing/using return value SplitData() • Outputting each element of the returned array on a new line Example program code Java String Code = "x=0;y=1;x=x+y;y++;"; String[] SplitDataArray = new String[10]; SplitDataArray = SplitData(Code); for(Integer x = 0; x < 4; x++){ System.out.println(SplitDataArray[x]); } VB.NET Dim Code As String = "x=0;y=1;x=x+y;y++;" Dim SplitDataArray() As String = SplitData(Code) For x = 0 To 3 Console.WriteLine(SplitDataArray(x)) Next Python Code = "x=0;y=1;x=x+y;y++;" SplitDataArray = SplitData(Code) for x in range(4): print(SplitDataArray[x])

3(b)(iv) [1 mark]

1 mark for output x=0 y=1 x=x+y y++ Example

Q12
May/Jun 2025 Paper 3 v1

The pseudocode algorithm checks whether a location in a stock file StockList.dat is empty or not. The location is given by the user. If the location is empty, a suitable message is displayed, otherwise the item stored at that location is displayed.

Complete this file-handling pseudocode algorithm.

DECLARE Location : INTEGER DECLARE Item : STRING DECLARE Continue : BOOLEAN DECLARE Answer : CHAR Continue TRUE

OPENFILE WHILE Continue OUTPUT "Enter a location between 1 and 500: " INPUT Location

GETRECORD IF Item = "" THEN OUTPUT "This record is missing." ELSE OUTPUT "The item in stock is ", ENDIF OUTPUT "Another location (Y or N)?" INPUT Answer IF Answer <> 'Y' THEN Continue FALSE ENDIF ENDWHILE

OUTPUT "End of program" 5 marks

The pseudocode algorithm checks whether a location in a stock file StockList.dat is empty or not. The location is given by the user. If the location is empty, a suitable message is displayed, otherwise the item stored at that location is displayed. Complete this file-handling pseudocode algorithm. DECLARE Location : INTEGER DECLARE Item : STRING DECLARE Continue : BOOLEAN DECLARE Answer : CHAR Continue TRUE OPENFILE WHILE Continue OUTPUT "Enter a location between 1 and 500: " INPUT Location GETRECORD IF Item = "" THEN OUTPUT "This record is missing." ELSE OUTPUT "The item in stock is ", ENDIF OUTPUT "Another location (Y or N)?" INPUT Answer IF Answer <> 'Y' THEN Continue FALSE ENDIF ENDWHILE OUTPUT "End of program" <span class="part-marks">5 marks</span>
Show mark scheme

12 [5 marks]

One mark for each correctly completed line ( Max 5 ) DECLARE Location : INTEGER DECLARE Item : STRING DECLARE Continue : BOOLEAN DECLARE Answer : CHAR  Continue TRUE OPENFILE "StockList.dat" FOR RANDOM WHILE Continue OUTPUT "Enter a location between 1 and 500: " INPUT Location SEEK "StockList.dat", Location GETRECORD "StockList.dat", Item IF Item = "" THEN OUTPUT "This record is missing" ELSE OUTPUT "The item in stock is ", Item ENDIF OUTPUT "Another location (Y or N)?" INPUT Answer IF Answer <> 'Y' THEN  Continue FALSE ENDIF ENDWHILE CLOSEFILE "StockList.dat" OUTPUT "End of program"

Q13
May/Jun 2025 Paper 3 v2

The pseudocode algorithm below uses random file access to copy 50 records from a live file CurrentResults.dat to a stored file StoredResults.dat one record at a time. It uses the user-defined type StudentResult.

TYPE StudentResult DECLARE LastName : STRING DECLARE FirstName : STRING DECLARE ExamGrade : STRING ENDTYPE

If any grades are missing in CurrentResults.dat, the text "Missing grade" is added to the ExamGrade field in StoredResults.dat

Complete this file handling pseudocode algorithm.

DECLARE Grade : StudentResult DECLARE Position : INTEGER

OPENFILE "StoredResults.dat" FOR RANDOM

SEEK "CurrentResults.dat", Position GETRECORD "CurrentResults.dat", Grade IF Grade.ExamGrade = "" THEN

ENDIF

NEXT Position CLOSEFILE "CurrentResults.dat" CLOSEFILE "StoredResults.dat" 5 marks

The pseudocode algorithm below uses random file access to copy 50 records from a live file CurrentResults.dat to a stored file StoredResults.dat one record at a time. It uses the user-defined type StudentResult. TYPE StudentResult DECLARE LastName : STRING DECLARE FirstName : STRING DECLARE ExamGrade : STRING ENDTYPE If any grades are missing in CurrentResults.dat, the text "Missing grade" is added to the ExamGrade field in StoredResults.dat Complete this file handling pseudocode algorithm. DECLARE Grade : StudentResult DECLARE Position : INTEGER OPENFILE "StoredResults.dat" FOR RANDOM SEEK "CurrentResults.dat", Position GETRECORD "CurrentResults.dat", Grade IF Grade.ExamGrade = "" THEN ENDIF NEXT Position CLOSEFILE "CurrentResults.dat" CLOSEFILE "StoredResults.dat" <span class="part-marks">5 marks</span>
Show mark scheme

13 [5 marks]

One mark for each correctly completed line DECLARE Grade : StudentResult DECLARE Position : INTEGER OPENFILE "CurrentResults.dat" FOR RANDOM OPENFILE "StoredResults.dat" FOR RANDOM  FOR Position 1 TO 50 SEEK "CurrentResults.dat", Position GETRECORD "CurrentResults.dat", Grade IF Grade.ExamGrade = "" THEN  Grade.ExamGrade "Missing grade" ENDIF SEEK "StoredResults.dat", Position PUTRECORD "StoredResults.dat", Grade NEXT Position CLOSEFILE "CurrentResults.dat" CLOSEFILE "StoredResults.dat"

Q11
May/Jun 2025 Paper 3 v3

The pseudocode algorithm below allows a user to input a new stock item. The random file is searched for the next empty location in the file and the new item is inserted there. A suitable message is displayed if the file is full.

Complete this pseudocode.

DECLARE Location : INTEGER DECLARE NewStock : STRING DECLARE CurrentStock : STRING DECLARE Stored : BOOLEAN DECLARE Max : INTEGER Max ← 100000 Stored ← FALSE Location ← 1

OUTPUT "Enter the new item you wish to store: " INPUT NewStock WHILE NOT Stored AND Location <= Max

GETRECORD "StockList.dat", IF CurrentStock = "" THEN

______ "StockList.dat", NewStock Stored ← TRUE ELSE Location ← Location + 1 ENDIF ENDWHILE

______ THEN OUTPUT "The new item has not been stored as the file was full." ENDIF CLOSEFILE "StockList.dat" 5 marks

The pseudocode algorithm below allows a user to input a new stock item. The random file is searched for the next empty location in the file and the new item is inserted there. A suitable message is displayed if the file is full. Complete this pseudocode. DECLARE Location : INTEGER DECLARE NewStock : STRING DECLARE CurrentStock : STRING DECLARE Stored : BOOLEAN DECLARE Max : INTEGER Max ← 100000 Stored ← FALSE Location ← 1 OUTPUT "Enter the new item you wish to store: " INPUT NewStock WHILE NOT Stored AND Location <= Max GETRECORD "StockList.dat", IF CurrentStock = "" THEN ______ "StockList.dat", NewStock Stored ← TRUE ELSE Location ← Location + 1 ENDIF ENDWHILE ______ THEN OUTPUT "The new item has not been stored as the file was full." ENDIF CLOSEFILE "StockList.dat" <span class="part-marks">5 marks</span>
Show mark scheme

11 [5 marks]

One mark for each correctly completed line DECLARE Location : INTEGER DECLARE NewStock : STRING DECLARE CurrentStock : STRING DECLARE Stored : BOOLEAN DECLARE Max : INTEGER  Max 100000  Stored FALSE  Location 1 OPENFILE "StockList.dat" FOR RANDOM OUTPUT "Enter the new item you wish to store" INPUT NewStock WHILE NOT Stored AND Location <= Max SEEK "StockList.dat", Location GETRECORD "StockList.dat", CurrentStock IF CurrentStock = "" THEN PUTRECORD "StockList.dat", NewStock  Stored TRUE ELSE  Location Location + 1 ENDIF ENDWHILE IF Stored = FALSE THEN OUTPUT "The new stock item has not been stored as the file was full" ENDIF CLOSEFILE "StockList.dat"

Q1
May/Jun 2025 Paper 4 v1

A program stores positive integers in a circular queue.

The queue is stored as a global 1D array of 20 integers with the identifier Queue . Each index is initialised with the data –1

The global variable HeadPointer, initialised to –1, points to the first element in the queue. The global variable TailPointer, initialised to –1, points to the last element in the queue. The global variable NumberItems, initialised to 0, stores the number of items in the queue.

(a) Write program code to declare and initialise Queue, HeadPointer, TailPointer and 2 marks

    NumberItems

Save your program as Question1_J25 .

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

(b) The function Enqueue() : 6 marks

  • takes an integer as a parameter

  • checks if the queue is full

  • returns FALSE if the queue is full

  • stores the parameter in the next position in the queue and returns TRUE if the queue is not full

  • updates the appropriate pointers and NumberItems

Write program code for Enqueue()

Save your program.

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

A program stores positive integers in a circular queue. The queue is stored as a global 1D array of 20 integers with the identifier `Queue` . Each index is initialised with the data `–1` The global variable `HeadPointer`, initialised to `–1`, points to the first element in the queue. The global variable `TailPointer`, initialised to `–1`, points to the last element in the queue. The global variable `NumberItems`, initialised to `0`, stores the number of items in the queue. ### (a) Write program code to declare and initialise `Queue`, `HeadPointer`, `TailPointer` and <span class="part-marks">2 marks</span> ``` NumberItems ``` Save your program as **Question1_J25** . Copy and paste the program code into part **1(a)** in the evidence document. ### (b) The function `Enqueue()` : <span class="part-marks">6 marks</span> - takes an integer as a parameter - checks if the queue is full - returns `FALSE` if the queue is full - stores the parameter in the next position in the queue and returns `TRUE` if the queue is **not** full - updates the appropriate pointers and `NumberItems` Write program code for `Enqueue()` 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 each • (global) Declaration of 1D array , 20 elements initialised with Queue –1 • (global) and initialised to , HeadPointer TailPointer –1 NumberItems

Queue[X] = -1;

1(b) [6 marks]

1 mark each • Function header (and close) taking 1 (integer) parameter and returning a Boolean value in all cases • Checking if queue is full ( ) and returning NumberItems = 20 FALSE • Checking if queue is empty ( ) then and updating NumberItems = 0 TailPointer • Incrementing and in appropriate place … TailPointer NumberItems • … looping back to 0 for if at end of structure TailPointer • Storing parameter in (after increment) and returning Queue[TailPointer]

Return False TailPointer = 0 HeadPointer = 0 Queue(TailPointer) = InputData

TailPointer = TailPointer + 1 If TailPointer = 20 Then TailPointer = 0 End If Queue(TailPointer) = InputData return false; TailPointer = 0; HeadPointer = 0; Queue[TailPointer] = InputData; TailPointer++; if(TailPointer == 20){ TailPointer = 0; } Queue[TailPointer] = InputData;

1(c) [3 marks]

1 mark each • Calling with 1 to 25 (inclusive) in order Enqueue() • … storing/using return value in selection …outputting with integer Successful integer correctly Console.WriteLine(x & "Successful " ) Console.WriteLine(x & "Unsuccessful ") System.out.println(X + "Successful "); System.out.println(X + "Unsuccessful ");

1(d) [6 marks]

1 mark each • header (and close) and checking if queue is empty ( Dequeue() NumberItems = 0 • Returning data at HeadPointer • Incrementing … HeadPointer • … and catching if = 20 to return to 0 • Decrementing NumberItems • Resetting and when queue is empty HeadPointer TailPointer

Return -1 ReturnValue = Queue(HeadPointer) HeadPointer = HeadPointer + 1 If HeadPointer >= 20 Then HeadPointer = 0 End If NumberItems = NumberItems – 1 If NumberItems = 0 Then HeadPointer = -1 TailPointer = -1

End If Return ReturnValue return -1; ReturnValue = Queue[HeadPointer]; HeadPointer++; if(HeadPointer >= 20){ HeadPointer = 0; } NumberItems--; if(NumberItems == 0){ HeadPointer = -1; TailPointer = -1; } return ReturnValue;

1(e)(i) [2 marks]

1 mark each • Calling twice Dequeue() • … outputting return value from both calls

1(e)(ii) [1 mark]

1 mark for output showing: • 1 to 20 with Successful 21 to 25 with Unsuccessful 1 and 2 output

Q2
May/Jun 2025 Paper 4 v1

A program reads data from a text file, splits the data depending on its content and stores the separated data into different files.

The text file TheData.txt contains 72 lines of data. Each line of data has an integer number and a string colour that are separated by a comma. For example, the first line in the file is:

    10,red

The integer is 10 and the string is "red"

The file contains six different colours: red, green, blue, orange, yellow, pink.

(a) The function ReadData() : 7 marks

  • prompts the user to enter a filename and reads this filename from the user

  • opens the file and reads each line of data into a 1D array

  • returns the populated 1D array.

The function needs to work for a file that contains an unknown number of lines.

Write program code for ReadData()

Save your program as Question2_J25 .

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

(b) The procedure SplitData() takes a 1D string array as a parameter with the identifier 6 marks

    DataArray

The procedure declares six 1D arrays: one array for each colour that appears in the file (red, green, blue, orange, yellow, pink).

The procedure accesses each string in DataArray . The data in each string is split into the integer and the colour. The integer is stored in the array that matches the colour.

For example, the first string in DataArray has the integer 10 and the colour red, so the integer 10 is stored in the array for the colour red.

Write program code for SplitData()

Save your program.

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

(c) The procedure StoreData() : 5 marks

  • takes two parameters: a 1D array DataToStore and a filename

  • opens the text file with the filename that is passed as a parameter

  • appends each item of data from DataToStore to a new line in the text file

  • uses exception handling when opening and writing data to the text file.

Write program code for StoreData()

Save your program.

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

(d) Each of the six colours has a blank text file where the numbers will be stored. The names of these six text files are: 2 marks

  • Blue.txt

  • Green.txt

  • Orange.txt

  • Pink.txt

  • Red.txt

  • Yellow.txt

The procedure SplitData() needs amending to call StoreData() six times, with each of the six colour arrays and the name of the text file that corresponds to that colour.

For example, StoreData() will be called with the red array and the file name "Red.txt"

Write program code to amend SplitData()

Save your program.

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

(e) The main program calls ReadData() and then SplitData()

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

Save your program.

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

(ii) Test your program. Input the text "TheData.txt" when prompted. 2 marks

Take a screenshot of the output(s) and a screenshot showing the content of the file that stores the red numbers.

Save your program.

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

A program reads data from a text file, splits the data depending on its content and stores the separated data into different files. The text file `TheData.txt` contains 72 lines of data. Each line of data has an integer number and a string colour that are separated by a comma. For example, the first line in the file is: ``` 10,red ``` The integer is `10` and the string is `"red"` The file contains six different colours: red, green, blue, orange, yellow, pink. ### (a) The function `ReadData()` : <span class="part-marks">7 marks</span> - prompts the user to enter a filename and reads this filename from the user - opens the file and reads each line of data into a 1D array - returns the populated 1D array. The function needs to work for a file that contains an unknown number of lines. Write program code for `ReadData()` Save your program as **Question2_J25** . Copy and paste the program code into part **2(a)** in the evidence document. ### (b) The procedure `SplitData()` takes a 1D string array as a parameter with the identifier <span class="part-marks">6 marks</span> ``` DataArray ``` The procedure declares six 1D arrays: one array for each colour that appears in the file (red, green, blue, orange, yellow, pink). The procedure accesses each string in `DataArray` . The data in each string is split into the integer and the colour. The integer is stored in the array that matches the colour. For example, the first string in `DataArray` has the integer `10` and the colour `red`, so the integer `10` is stored in the array for the colour red. Write program code for `SplitData()` Save your program. Copy and paste the program code into part **2(b)** in the evidence document. ### (c) The procedure `StoreData()` : <span class="part-marks">5 marks</span> - takes **two** parameters: a 1D array `DataToStore` and a filename - opens the text file with the filename that is passed as a parameter - appends each item of data from `DataToStore` to a new line in the text file - uses exception handling when opening and writing data to the text file. Write program code for `StoreData()` Save your program. Copy and paste the program code into part **2(c)** in the evidence document. ### (d) Each of the six colours has a blank text file where the numbers will be stored. The names of these six text files are: <span class="part-marks">2 marks</span> - `Blue.txt` - `Green.txt` - `Orange.txt` - `Pink.txt` - `Red.txt` - `Yellow.txt` The procedure `SplitData()` needs amending to call `StoreData()` **six** times, with each of the **six** colour arrays and the name of the text file that corresponds to that colour. For example, `StoreData()` will be called with the red array and the file name `"Red.txt"` Write program code to amend `SplitData()` Save your program. Copy and paste the program code into part **2(d)** in the evidence document. ### (e) The main program calls `ReadData()` and then `SplitData()` #### (i) Write program code for the main program. <span class="part-marks">3 marks</span> Save your program. Copy and paste the program code into part **2(e)(i)** in the evidence document. #### (ii) Test your program. Input the text `"TheData.txt"` when prompted. <span class="part-marks">2 marks</span> Take a screenshot of the output(s) and a screenshot showing the content of the file that stores the red numbers. Save your program. Copy and paste the screenshot(s) into part **2(e)(ii)** in the evidence document.
Show mark scheme

2(a) [7 marks]

1 mark each to max 7 • Function header (and end) • Prompt to enter filename and reading input • Opening the file (to read) and closing the file in an appropriate place • Looping until EOF … • … reading each line in the file … • … (removing line break and) inserting in array • Returning populated array • Exception handling try catch with appropriate output

Dim FileReader As New System.IO.StreamReader(FileName) While Not FileReader.EndOfStream DataList(NumberItems) = FileReader.ReadLine() NumberItems = NumberItems + 1 End While FileReader.Close() Console.WriteLine("Cannot open or read from file")

FileReader f = new FileReader(FileName); try{ BufferedReader Reader = new BufferedReader(f); String Line = Reader.readLine(); Line = Line.replace("\n",""); while (Line != null){ DataList[NumberItems] = Line; NumberItems++; Line = Reader.readLine(); if(Line != null){ Line = Line.replace("\n",""); } } Reader.close(); }catch(IOException ex){ } System.out.println("File not found");

2(b) [6 marks]

1 mark each • Procedure header (and end) taking (1D array) (of strings) as a parameter DataArray • Declaration/use of 6 1D arrays (equivalent), one for each colour • Looping through each line in parameter … DataArray • … splitting by comma • Comparing 2nd value/colour to each colour to select array … • … storing 1st value/integer in correct array

TempDataFromFile = (DataArray(x)).Split(",") DataList(x, 0) = TempDataFromFile(0) DataList(x, 1) = TempDataFromFile(1) If DataList(x, 1) = "red" Then Red(RedNumber) = DataList(x, 0) RedNumber = RedNumber + 1 ElseIf DataList(x, 1) = "green" Then Green(GreenNumber) = DataList(x, 0) GreenNumber = GreenNumber + 1 ElseIf DataList(x, 1) = "blue" Then Blue(BlueNumber) = DataList(x, 0) BlueNumber = BlueNumber + 1 ElseIf DataList(x, 1) = "orange" Then Orange(OrangeNumber) = DataList(x, 0) OrangeNumber = OrangeNumber + 1 ElseIf DataList(x, 1) = "yellow" Then Yellow(YellowNumber) = DataList(x, 0) YellowNumber = YellowNumber + 1 ElseIf DataList(x, 1) = "pink" Then Pink(PinkNumber) = DataList(x, 0) PinkNumber = PinkNumber + 1 End If

x = x + 1

x = x + 1;

2(c) [5 marks]

1 mark each • Procedure header taking (1D) array and filename as parameters, opening file to append place) • Looping through each item in array parameter … • … writing to the file • … with new line break between each line • Using exception handling try and catch with suitable output While DataToStore(x) IsNot Nothing FileWriter.WriteLine(DataToStore(x)) x = x + 1 End While FileWriter.Close() Console.WriteLine("Cannot open or write to file")

2(d) [2 marks]

1 mark each • Calling with one array and filename StoreData • Calling with remaining 5 arrays and filename StoreData

2(e)(i) [3 marks]

1 mark each • Calling … ReadData() • … and storing/using return value • Calling with returned array as a parameter SplitData()

2(e)(ii) [2 marks]

1 mark screenshots showing • Prompt and input of filename TheData.txt • Screenshot of data in red file. Filename must be shown in same screenshot as data

Q1
May/Jun 2025 Paper 4 v2

A program reads data from a text file and stores it in a stack. The stack Stack is stored as a 1D array of up to 20 elements. The pointer TopOfStack stores the index of the last element stored in the stack.

(a) Stack is a global array of strings with all elements initialised to "-1" TopOfStack is a global variable initialised to –1 Write program code to declare and initialise Stack and TopOfStack Save your program as Question1_J25 . 2 marks

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

(b) The function Push() takes a string parameter and attempts to store it on the stack. 4 marks

The function returns –1 if the stack is full.

The function returns 1 if the parameter is successfully pushed onto the stack.

Write program code for Push()

Save your program.

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

A program reads data from a text file and stores it in a stack. The stack `Stack` is stored as a 1D array of up to 20 elements. The pointer `TopOfStack` stores the index of the last element stored in the stack. ### (a) `Stack` is a global array of strings with all elements initialised to `"-1"` `TopOfStack` is a global variable initialised to `–1` Write program code to declare and initialise `Stack` and `TopOfStack` Save your program as **Question1_J25** . <span class="part-marks">2 marks</span> Copy and paste the program code into part **1(a)** in the evidence document. ### (b) The function `Push()` takes a string parameter and attempts to store it on the stack. <span class="part-marks">4 marks</span> The function returns `–1` if the stack is full. The function returns `1` if the parameter is successfully pushed onto the stack. Write program code for `Push()` 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 each • (Global) as 1D array (of strings) with 20 elements initialised to string Stack • (Global) initialised to TopOfStack –1 for(Integer X = 0; X < 20; X++){ Stack[X] = "-1"; } TopOfStack = -1;

1(b) [1 mark]

1 mark each • function header (and end where appropriate) taking one (string) parameter Push • Checking if stack is full and returning integer –1 • (Otherwise) Incrementing TopOfStack • Storing parameter in the incremented the stack at and returning integer TopOfStack if (TopOfStack == 19){ return -1; }else{ TopOfStack++; Stack[TopOfStack] = Data; return 1; }

1(c) [4 marks]

1 mark each • Function header (and end where appropriate) and returning a value in all cases. • Checking if stack is empty and returning string "–1" • (Otherwise) Decrementing TopOfStack • Returning element in stack at before is decremented TopOfStack TopOfStack if (TopOfStack == -1){ return "-1"; }else{ String ReturnValue = Stack[TopOfStack]; TopOfStack--; return ReturnValue; }

1(d) [6 marks]

1 mark each • Procedure header (and end where appropriate) taking one (string) parameter • Opening the file with the filename parameter and closing the file in an appropriate place • Looping through to end of file and reading in each line ... • … calling once with each read in value … Push() • … if any return value from is integer outputting Push() –1 "Stack full" • Exception handling for opening and reading from file with appropriate catch and output Integer ReturnValue; try{ FileReader f = new FileReader(FileName); try{ BufferedReader Reader = new BufferedReader(f); String Line= Reader.readLine(); Line = Line.replace("\n",""); while (Line != null){ Line = Line.replace("\n",""); ReturnValue = Push(Line); if (ReturnValue == -1){ System.out.println("Stack full"); } Line = Reader.readLine(); } Reader.close(); }catch(IOException ex){} }catch(FileNotFoundException e){ System.out.println("File not found"); }

1(e) [7 marks]

1 mark for: • function header (and end where appropriate) Calculate() • Looping until the stack is empty • Calling repeatedly within loop and storing/using return value Pop() • … working out if return value from call is an operator or a number / alternating between operator and number Pop() • Select to determine if the operator is +, -, /, * or ^ and attempt the matching calculation • … performing correct calculation using operator, number • … updating total from previous loops and returning this final value Double Total = Double.parseDouble(Pop()); String ReturnValue = ""; String LastOperator = ""; Boolean OperatorFlag = true; Integer TheData = 0; while(ReturnValue != "-1"){ ReturnValue = Pop(); if(OperatorFlag == false){ TheData = Integer.parseInt(ReturnValue); if(LastOperator.compareTo("+")==0){ Total = Total + TheData; }else if(LastOperator.compareTo("-")==0){ Total = Total - TheData; }else if(LastOperator.compareTo("*")==0){ Total = Total * TheData; }else if(LastOperator.compareTo("/")==0){ Total = Total / TheData; }else if(LastOperator.compareTo("^")==0){ Total = Math.pow(Total, TheData); } OperatorFlag = true;

}else{ LastOperator = ReturnValue; OperatorFlag = false; } } return Total;

1(f)(i) [2 marks]

1 mark each • Taking a filename as input and calling with input ReadData() • Calling and outputting the return value Calculate()

1(f)(ii) [2 marks]

1 mark for screenshot showing input of and output of 131 StackData.txt 1 mark for screenshot showing input of and output of 320 SecondStack.txt

Q2
May/Jun 2025 Paper 4 v2

A program stores data in a 1D array of records, HashTable . The array has space for 200 records. Each data item is stored in a specific index of the array that is calculated using an algorithm. The index is calculated from the key field using the formula: Key MOD 200

If two key fields generate the same index, there is a collision. Any records that have a collision are stored in a second array, Spare . This array has space for 100 records. When a collision is detected, the record is stored in the next free space in Spare .

(a) The pseudocode record format is: 2 marks

    TYPE NewRecord
    DECLARE Key : INTEGER
    DECLARE Item1 : INTEGER
    DECLARE Item2 : INTEGER
    ENDTYPE

Write program code to declare the record type NewRecord

If your chosen programming language does not support record formats, a class can be used instead.

Save your program as Question2_J25 .

Copy and paste the program code into part 2(a) in the evidence document. (b) (i) Write program code to declare the global arrays HashTable and Spare 1 mark

Save your program.

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

(ii) An empty record has the integer –1 stored in each field. 2 marks

The procedure Initialise() stores an empty record in each element in HashTable and Spare

Write program code for Initialise()

Save your program.

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

(c) The hash value is calculated from the key field using the formula: Key MOD 200 The function CalculateHash() takes a key field as a parameter and calculates and returns the hash value for the key field. 2 marks

Write program code for CalculateHash()

Save your program.

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

(d) The procedure InsertIntoHash() : 6 marks

  • takes a record of type NewRecord as a parameter

  • uses CalculateHash() to calculate the hash value for the key field in the record

  • checks if the hash value index in HashTable currently stores an empty record

  • if the index stores an empty record, store the parameter in this index

  • if the index does not store an empty record, store the parameter in Spare

You can assume there will always be enough space in Spare to store any collisions.

Write program code for InsertIntoHash()

Save your program.

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

(e) The text file HashData.txt stores up to 200 rows of data to be stored into the hash table. 5 marks

Each row contains three integer numbers separated by commas.

The first number is the key field, the second number is item 1 and the third number is item 2.

For example:

The first row in the text file contains: 646, 12, 568

The key field is 646, item 1 is 12 and item 2 is 568

The procedure CreateHashTable() :

  • opens the file HashData.txt

  • creates a record for each row of data in the file

  • calls InsertIntoHash() with each record.

Write program code for CreateHashTable()

Save your program.

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

(f) (i) The procedure PrintSpare() outputs the key field of each element in the array Spare that does not contain an empty record. 2 marks

Write program code for PrintSpare()

Save your program.

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

(ii) The main program should call the procedure to initialise the arrays, call the procedure to create the hash table and then call the procedure to output the contents of the array 1 mark

      Spare

Write program code for the main program.

Save your program.

Copy and paste the program code into part 2(f)(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(f)(iii) in the evidence document.

A program stores data in a 1D array of records, `HashTable` . The array has space for 200 records. Each data item is stored in a specific index of the array that is calculated using an algorithm. The index is calculated from the key field using the formula: `Key MOD 200` If two key fields generate the same index, there is a collision. Any records that have a collision are stored in a second array, `Spare` . This array has space for 100 records. When a collision is detected, the record is stored in the next free space in `Spare` . ### (a) The pseudocode record format is: <span class="part-marks">2 marks</span> ``` TYPE NewRecord DECLARE Key : INTEGER DECLARE Item1 : INTEGER DECLARE Item2 : INTEGER ENDTYPE ``` Write program code to declare the record type `NewRecord` If your chosen programming language does **not** support record formats, a class can be used instead. Save your program as **Question2_J25** . Copy and paste the program code into part **2(a)** in the evidence document. **(b) (i)** Write program code to declare the global arrays `HashTable` and `Spare` <span class="part-marks">1 mark</span> Save your program. Copy and paste the program code into part **2(b)(i)** in the evidence document. #### (ii) An empty record has the integer `–1` stored in each field. <span class="part-marks">2 marks</span> The procedure `Initialise()` stores an empty record in each element in `HashTable` and `Spare` Write program code for `Initialise()` Save your program. Copy and paste the program code into part **2(b)(ii)** in the evidence document. ### (c) The hash value is calculated from the key field using the formula: `Key MOD 200` The function `CalculateHash()` takes a key field as a parameter and calculates and returns the hash value for the key field. <span class="part-marks">2 marks</span> Write program code for `CalculateHash()` Save your program. Copy and paste the program code into part **2(c)** in the evidence document. ### (d) The procedure `InsertIntoHash()` : <span class="part-marks">6 marks</span> - takes a record of type `NewRecord` as a parameter - uses `CalculateHash()` to calculate the hash value for the key field in the record - checks if the hash value index in `HashTable` currently stores an empty record - if the index stores an empty record, store the parameter in this index - if the index does **not** store an empty record, store the parameter in `Spare` You can assume there will always be enough space in `Spare` to store any collisions. Write program code for `InsertIntoHash()` Save your program. Copy and paste the program code into part **2(d)** in the evidence document. ### (e) The text file `HashData.txt` stores up to 200 rows of data to be stored into the hash table. <span class="part-marks">5 marks</span> Each row contains three integer numbers separated by commas. The first number is the key field, the second number is item 1 and the third number is item 2. For example: The first row in the text file contains: `646`, `12`, `568` The key field is `646`, item 1 is `12` and item 2 is `568` The procedure `CreateHashTable()` : - opens the file `HashData.txt` - creates a record for each row of data in the file - calls `InsertIntoHash()` with each record. Write program code for `CreateHashTable()` Save your program. Copy and paste the program code into part **2(e)** in the evidence document. ### (f) **(i)** The procedure `PrintSpare()` outputs the key field of each element in the array `Spare` that does **not** contain an empty record. <span class="part-marks">2 marks</span> Write program code for `PrintSpare()` Save your program. Copy and paste the program code into part **2(f)(i)** in the evidence document. #### (ii) The main program should call the procedure to initialise the arrays, call the procedure to create the hash table and then call the procedure to output the contents of the array <span class="part-marks">1 mark</span> ``` Spare ``` Write program code for the main program. Save your program. Copy and paste the program code into part **2(f)(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(f)(iii)** in the evidence document.
Show mark scheme

2(a) [2 marks]

1 mark each • Record/class declared NewRecord • 3 variables within structure (all integer) private Integer Key; private Integer Item1; private Integer Item2; public NewRecord(Integer pKey, Integer pItem1, Integer pItem2){ Key = pKey; Item1 = pItem1; Item2 = pItem2; } public Integer GetKey(){ return Key; } public Integer GetItem1(){ return Item1; } public Integer GetItem2(){ return Item2; }}

2(b)(i) [1 mark]

1 mark for • (200 records) and (100 records) declared as (global) arrays HashTable Spare

2(b)(ii) [2 marks]

1 mark each • Procedure header (and close where appropriate) that initialises all elements in both arrays … Initialise() • … to an empty record with –1 in each of the 3 fields/elements NewRecord EmptyRecord = new NewRecord(-1,-1,-1); for(Integer X = 0; X < 200; X++){ HashTable[X] = EmptyRecord; } for(Integer X = 0; X < 100; X++){ Spare[X] = EmptyRecord; }

2(c) [2 marks]

1 mark each • Function header (and close where appropriate), taking one (integer) parameter • Calculation of parameter MOD 200 return(TheKey % 200);

2(d) [6 marks]

1 mark each: • Procedure header (and end where appropriate) taking one record as a parameter • Calling with key from parameter record and storing/using return value CalculateHash() • Checking if at return value from is empty HashTable CalculateHash • … if it is empty, store parameter in location • … otherwise, locating next free space in … Spare • … and storing in that index only (i.e. not in all other free spaces)

Integer HashValue = CalculateHash(TheRecord.GetKey()); if(HashTable[HashValue].GetKey().equals(-1)){ HashTable[HashValue] = TheRecord; }else{ for(Integer X = 0; X < 99; X++){ if(Spare[X].GetKey().equals(-1)){ Spare[X] = TheRecord; X = 99; } } }

2(e) [5 marks]

1 mark each to max 5 • Procedure header (and end where appropriate), opening and closing file • Reading in all lines of data … • … splitting each line by commas • Creating record with correct values with each line read in from file • Calling with each record they have created InsertIntoHash() • Exception handling for opening and reading from file with appropriate catch and output. String[] Data = new String[3]; Integer NewKey; Integer NewItem1; Integer NewItem2; try{ FileReader File = new FileReader("HashData.txt"); try{ BufferedReader Reader = new BufferedReader(File); String Line= Reader.readLine(); while (Line != null){ Line = Line.replace("\n",""); Data = Line.split(","); NewKey = Integer.parseInt(Data[0]); NewItem1 = Integer.parseInt(Data[1]); NewItem2 = Integer.parseInt(Data[2]); NewRecord ReadData = new NewRecord(NewKey, NewItem1, NewItem2); InsertIntoHash(ReadData); Line= Reader.readLine(); } Reader.close(); }catch(IOException ex){} }catch(FileNotFoundException e){System.out.println("File not found");}

2(f)(i) [2 marks]

1 mark each • Procedure header (and end where appropriate) and looping through each element in • … checking if record is empty and outputting key field if not empty Integer X = 0; while(Spare[X].GetKey() != -1){ System.out.println(Spare[X].GetKey()); X++; }

2(f)(ii) [1 mark]

1 mark for calling then then Initialise() CreateHashTable() PrintSpare()

2(f)(iii) [1 mark]

1 mark for output

Q1
May/Jun 2025 Paper 4 v3

A program reads data from a text file and stores it in a queue. The linear queue Queue is stored as a 1D array of up to 50 elements. The queue has the following pointers:

  • HeadPointer - this stores the index of the first element in the queue, initialised to –1

  • TailPointer - this stores the index of the last element in the queue, initialised to –1

(a) Queue is a global array of 50 integers with all elements initialised to –1 in the main program. 3 marks

The two pointers are declared as global variables and initialised to –1

Write program code to declare and initialise Queue, HeadPointer and TailPointer

Save your program as Question1_J25 .

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

(b) The function Enqueue() : 6 marks

  • takes an integer parameter to store in the next position in the queue

  • returns FALSE if the queue is full and the parameter cannot be stored in the queue

  • returns TRUE if the parameter is stored in the queue

  • updates the pointers where appropriate.

Write program code for Enqueue()

Save your program.

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

A program reads data from a text file and stores it in a queue. The linear queue `Queue` is stored as a 1D array of up to 50 elements. The queue has the following pointers: - `HeadPointer` - this stores the index of the first element in the queue, initialised to `–1` - `TailPointer` - this stores the index of the last element in the queue, initialised to `–1` ### (a) `Queue` is a global array of 50 integers with all elements initialised to `–1` in the main program. <span class="part-marks">3 marks</span> The **two** pointers are declared as global variables and initialised to `–1` Write program code to declare and initialise `Queue`, `HeadPointer` and `TailPointer` Save your program as **Question1_J25** . Copy and paste the program code into part **1(a)** in the evidence document. ### (b) The function `Enqueue()` : <span class="part-marks">6 marks</span> - takes an integer parameter to store in the next position in the queue - returns `FALSE` if the queue is full and the parameter cannot be stored in the queue - returns `TRUE` if the parameter is stored in the queue - updates the pointers where appropriate. Write program code for `Enqueue()` 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 each • (Global) array with 50 integer elements … Queue • … all initialised to –1 • (Global) and initialised with HeadPointer TailPointer –1

Queue(x) = -1

1(b) [6 marks]

1 mark each • Function header (and end) taking one (integer) parameter Enqueue() • Checking if is full … Queue • …returning if full and if not full FALSE TRUE • (Otherwise) storing data item at (check incrementing) TailPointer + 1 • Incrementing TailPointer • Checking if this is the first element and incrementing/storing 0 in HeadPointer

TailPointer = TailPointer + 1 Queue(TailPointer) = DataValue If HeadPointer = -1 Then HeadPointer = 0 End If Return True Return False

1(c) [5 marks]

1 mark each • Function header (and close) and returning appropriate value in all cases. Dequeue() • Checking if queue is empty … • … and returning if empty –1 • Accessing and returning element at (before Queue[HeadPointer] HeadPointer • Incrementing HeadPointer

ReturnValue = Queue(HeadPointer) HeadPointer = HeadPointer + 1 Return ReturnValue Return -1

1(d) [6 marks]

1 mark each • header (and end) and opening the file to read and closing file in appropriate place CreateQueue() • Looping until end of file • Reading in each/all lines (and converting to integer and removing new line) • … calling once with each value … Enqueue() • … checking return value and outputting if full (can output once or many times) "Queue full" • Exception try, catch with appropriate output. All file access within try

Dim FileReader As New System.IO.StreamReader("QueueData.txt") While Not FileReader.EndOfStream ReadData = FileReader.ReadLine() ReturnValue = Enqueue(ReadData) If ReturnValue = False Then Console.WriteLine("Queue full") End If End While FileReader.Close() Console.WriteLine("Cannot open or read file")

1(e)(i) [5 marks]

1 mark each • Calling CreateQueue() • Calling and storing/using return value … Dequeue() • … repeatedly until return value is –1 • … adding together all return values to create a total within the loop … • … outputting the total

Total = Total + ReturnValue

1(e)(ii) [1 mark]

1 mark for screenshot showing 3059

Q2
May/Jun 2025 Paper 4 v3

A program sorts the data in the 1D array DataArray and searches DataArray for specific values.

DataArray stores 14 integer values and is declared local to the main program.

(a) Write program code to create DataArray and initialise it with the following data values in the order they are written: 1 mark

      0  3  4  56  67  44  43  32  31  345  45  6  54  1

Save your program as Question2_J25 .

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

(b) The function InsertionSort() takes an array of integers as a parameter. The function sorts the data in the array into ascending numerical order using an insertion sort. The function returns the sorted array. 5 marks

Write program code for InsertionSort()

You must not use any inbuilt sorting functions for your programming language.

Save your program.

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

(c) The procedure OutputArray() takes an array of integers as a parameter. The procedure outputs each element in the array from the first element to the last element. The output is on one line with a space between each number. 2 marks

An example output is:

           "0 3 4 56 67 44 43 32 31 345 45 6 54 1"

Write program code for OutputArray()

Save your program.

Copy and paste the program code into part 2(c) in the evidence document. (d) (i) The main program needs extending to: 2 marks

  • output the content of the unsorted array using OutputArray()

  • sort the array using InsertionSort()

  • output the content of the sorted array using OutputArray()

Write program code to extend the main program.

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 function Search() performs a binary search to find ItemToFind in DataArray The function takes two parameters: 6 marks

  • DataArray, an array of integers

  • ItemToFind, an integer to find in DataArray

The function returns:

  • the index of ItemToFind if it is in DataArray

  • –1 if ItemToFind is not in DataArray

Write program code for Search()

You must not use any inbuilt searching functions for your programming language.

Save your program.

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

(f) (i) The main program needs extending to call Search() with the sorted array four times: 2 marks

  • the first time to find the index of the integer 0

  • the second time to find the index of the integer 345

  • the third time to find the index of the integer 67

  • the fourth time to find the index of the integer 2

If the integer is found in the array, output an appropriate message that includes the index. If the integer is not found, output that it was not found.

Write program code to extend the main program.

Save your program.

Copy and paste the program code into part 2(f)(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(f)(ii) in the evidence document.

A program sorts the data in the 1D array `DataArray` and searches `DataArray` for specific values. `DataArray` stores 14 integer values and is declared local to the main program. ### (a) Write program code to create `DataArray` and initialise it with the following data values in the order they are written: <span class="part-marks">1 mark</span> ``` 0 3 4 56 67 44 43 32 31 345 45 6 54 1 ``` Save your program as **Question2_J25** . Copy and paste the program code into part **2(a)** in the evidence document. ### (b) The function `InsertionSort()` takes an array of integers as a parameter. The function sorts the data in the array into ascending numerical order using an insertion sort. The function returns the sorted array. <span class="part-marks">5 marks</span> Write program code for `InsertionSort()` You must **not** use any inbuilt sorting functions for your programming language. Save your program. Copy and paste the program code into part **2(b)** in the evidence document. ### (c) The procedure `OutputArray()` takes an array of integers as a parameter. The procedure outputs each element in the array from the first element to the last element. The output is on one line with a space between each number. <span class="part-marks">2 marks</span> An example output is: ``` "0 3 4 56 67 44 43 32 31 345 45 6 54 1" ``` Write program code for `OutputArray()` Save your program. Copy and paste the program code into part **2(c)** in the evidence document. **(d) (i)** The main program needs extending to: <span class="part-marks">2 marks</span> - output the content of the unsorted array using `OutputArray()` - sort the array using `InsertionSort()` - output the content of the sorted array using `OutputArray()` Write program code to extend the main program. 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 function `Search()` performs a binary search to find `ItemToFind` in `DataArray` The function takes **two** parameters: <span class="part-marks">6 marks</span> - `DataArray`, an array of integers - `ItemToFind`, an integer to find in `DataArray` The function returns: - the index of `ItemToFind` if it is in `DataArray` - `–1` if `ItemToFind` is **not** in `DataArray` Write program code for `Search()` You must **not** use any inbuilt searching functions for your programming language. Save your program. Copy and paste the program code into part **2(e)** in the evidence document. ### (f) **(i)** The main program needs extending to call `Search()` with the sorted array **four** times: <span class="part-marks">2 marks</span> - the first time to find the index of the integer 0 - the second time to find the index of the integer 345 - the third time to find the index of the integer 67 - the fourth time to find the index of the integer 2 If the integer is found in the array, output an appropriate message that includes the index. If the integer is **not** found, output that it was **not** found. Write program code to extend the main program. Save your program. Copy and paste the program code into part **2(f)(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(f)(ii)** in the evidence document.
Show mark scheme

2(a) [1 mark]

1 mark for array declared with data values: 0 3 4 56 67 44 43 32 31 345 45 6 54 1

2(b) [5 marks]

1 mark each • header (and close) taking array as a parameter and returning (attempt at) sorted array InsertionSort() • Looping through/for each element • Extracting element and comparing to sorted list … • … moving elements in sorted list • … and inserting element in correct position (ascending order)

Return DataArray CurrentValue = DataArray(X) Y = X - 1 While Y >= 0 AndAlso CurrentValue < DataArray(Y) DataArray(Y + 1) = DataArray(Y) Y = Y - 1 End While DataArray(Y + 1) = CurrentValue

2(c) [2 marks]

1 mark each • header (and close) taking an array parameter and outputting the array contents … OutputArray() • … in correct format

If DataArray(X) <> -1 Then Output = Output & DataArray(X) & " " End If X = X + 1

2(d)(i) [2 marks]

1 mark each • Calling with array parameter and storing/using return array InsertionSort() • … calling with array parameter before and after OutputArray() InsertionSort()

2(d)(ii) [1 mark]

1 mark for output showing unsorted then sorted array e.g.

2(e) [6 marks]

1 mark each • header (and close) taking array and integer as parameters Search() • Looping/recursive calls until no elements left/Low<=High and returning –1 if not found • … calculating middle index and accessing this value • … comparison of array at middle value to integer parameter • … if they are equal return mid • … if array[mid] < parameter update low to middle + 1, if array[mid] > parameter update high to middle – 1 // recursive call with updated low and updated high

Middle = (High + Low) \ 2 If DataArray(Middle) < ItemToFind Then Low = Middle + 1 ElseIf DataArray(Middle) > ItemToFind Then High = Middle - 1 Else Return Middle End If

2(f)(i) [2 marks]

1 mark each • Calling with all four sets of values 0 345 67 2 Search() • … outputting 'not found' or index in appropriate message each time

2(f)(ii) [1 mark]

1 mark for output showing locations for first 3 and not found for 4th

Q1
Oct/Nov 2024 Paper 4 v1

A program sorts string data using different sorting methods.

(a) The text file Data.txt stores string data items. Each data item is on a new line in the text file. 6 marks

The function ReadData() :

  • has a local array of strings that can store 45 items

  • reads each line of data and stores it in the array

  • returns the array.

Write program code for the function ReadData() .

Save your program as Question1_N24 .

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

A program sorts string data using different sorting methods. ### (a) The text file `Data.txt` stores string data items. Each data item is on a new line in the text file. <span class="part-marks">6 marks</span> The function `ReadData()` : - has a local array of strings that can store 45 items - reads each line of data and stores it in the array - returns the array. Write program code for the function `ReadData()` . Save your program as **Question1_N24** . Copy and paste the program code into part **1(a)** in the evidence document.
Show mark scheme

1(a)

FileReader.Close() Catch ex As Exception Console.WriteLine("No file found") End Try Return Colours End Function Java public static String[] ReadData(){ String TextFile = "Data.txt"; String Colours[] = new String[45]; try{ FileReader f = new FileReader(TextFile); BufferedReader Reader = new BufferedReader(f); for(Integer X = 0; X < 45; X++){ try{ Colours[X] = Reader.readLine(); }catch(IOException ex){} } try{ Reader.close(); }catch(IOException ex){} return Colours; }catch(FileNotFoundException e){ System.out.println("File not found"); } return Colours; }

1(b)(i) [2 marks]

1 mark each • Function header (and end where appropriate) taking (min) one parameter • Looping through each parameter array element, concatenating with space and returning Python def FormatArray(DataArray): OutputText = "" for x in range(0, 45): OutputText = OutputText + DataArray[x] + " " return OutputText VB.NET Function FormatArray(DataArray) Dim OutputText As String = "" For X = 0 To 44 OutputText = OutputText & DataArray(X) & " " Next Return OutputText End Function Java public static String FormatArray(String[] DataArray){ String OutputText = ""; for(Integer X = 0; X < 45; X++){ OutputText = OutputText + DataArray[X] + " "; } return OutputText; }

1(b)(ii) [3 marks]

1 mark each: • Calling and storing returned array … ReadData() • … calling with returned array FormatArray() • Outputting return value from FormatArray() Python Colours = ReadData() #string array print(FormatArray(Colours)) VB.NET Dim Colours(45) As String Colours = ReadData() Console.WriteLine(FormatArray(Colours)) Java String[] Colours = new String[45]; Colours = ReadData(); System.out.println(FormatArray(Colours));

1(b)(iii) [1 mark]

1 mark for output showing all colours in one string e.g.

1(c)

Java public static Integer CompareStrings(String First, String Second){ Integer Count = 0; while(true){ if(First.substring(Count, Count + 1).compareTo(Second.substring(Count, Count + 1)) < 0){ return 1; }else if(First.substring(Count, Count + 1).compareTo(Second.substring(Count, Count + 1))>0){ return 2; }else{ Count++; } } }

1(d)(i)

Temp = DataArray[Y]; DataArray[Y] = DataArray[Y+1]; DataArray[Y+1] = Temp; } } } return DataArray; }

1(d)(ii) [2 marks]

1 mark each • Calling with array as parameter and using/storing return value Bubble() • Calling with return value from and outputting return value FormatArray() Bubble() Python BubbleSorted = Bubble(Colours) print(FormatArray(BubbleSorted)) VB.NET Dim BubbleSorted(45) As String BubbleSorted = Bubble(Colours) Console.WriteLine(FormatArray(BubbleSorted)) Java String[] BubbleSorted = new String[45]; BubbleSorted = Bubble(Colours); System.out.println(FormatArray(BubbleSorted));

1(d)(iii) [1 mark]

1 mark for sorted data e.g.

Q3
Oct/Nov 2024 Paper 4 v1

A linked list stores positive integer data in a 2D array. The first dimension of the array stores the integer data. The second dimension of the array stores the pointer to the next node in the linked list.

A linked list node with no data is initialised with the integer –1 . These nodes are linked together as an empty list. A pointer of –1 identifies that node as the last node.

The linked list can store 20 nodes.

The global 2D array LinkedList stores the linked list.

LinkedList is initialised as an empty list. The data in each node is initialised to –1 . Each node’s pointer stores the index of the next node. The last node stores the pointer value –1, which indicates it is the last node.

The global variable FirstEmpty stores the index of the first element in the empty list. This is the first node in the empty linked list when it is initialised, which is index 0 .

The global variable FirstNode stores the index of the first element in the linked list. There is no data in the linked list when it is initialised, so FirstNode is initialised to –1 .

This diagram shows the content of the initialised array.

  FirstEmpty = 0
  FirstNode = –1

|Index|Data|Pointer|
|---|---|---|
|`0`|`-1`|`1`|
|`1`|`-1`|`2`|
|`2`|`-1`|`3`|
|`3`|`-1`|`4`|
|`4`|`-1`|`5`|
||||
|`19`|<br>`-1`|<br>`-1`|

(a) Write program code for the main program to declare and initialise LinkedList, FirstNode and FirstEmpty . 2 marks

Save your program as Question3_N24 .

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

(b) The procedure InsertData() takes five positive integers as input from the user and inserts these into the linked list. 6 marks

Each data item is inserted at the front of the linked list.

The table shows the steps to follow depending on the state of the linked list:
Linked list state Steps
not full insert the data in the index pointed to byFirstEmpty
change the pointer to the index pointed to byFirstNode
change the values ofFirstNode andFirstEmpty
full end the procedure

Any node that is at the end of the linked list has a pointer of –1 .

Write program code for InsertData() .

Save your program.

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

(c) The procedure OutputLinkedList() outputs the data in the linked list in order by following the pointers from FirstNode .

(i) Write program code for OutputLinkedList() . 2 marks

Save your program.

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

(ii) Amend the main program to call InsertData() and then OutputLinkedList() . 1 mark

Save your program.

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

(iii) Test your program with the test data: 1 mark

5 1 2 3 8

Take a screenshot of the output.

Save your program.

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

(d) The procedure RemoveData() removes a node from the linked list.

The procedure takes the data item to be removed from the linked list as a parameter.

The procedure checks each node in the linked list, starting with the node FirstNode, until it finds the node to be removed. This node is added to the empty list, and pointers are changed as appropriate. The procedure only removes the first occurrence of the parameter.

Assume that the data item being removed is in the linked list.

(i) Write program code for RemoveData() . 5 marks

Save your program.

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

(ii) Amend the main program to: 1 mark

  • call RemoveData() with the parameter 5

  • output the word "After"

  • call OutputLinkedList() .

Save your program.

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

(iii) Test your program with both sets of given test data: 1 mark

Test data set 1: 5 6 8 9 5

Test data set 2: 10 7 8 5 6

Take a screenshot of each output.

Save your program.

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

A linked list stores positive integer data in a 2D array. The first dimension of the array stores the integer data. The second dimension of the array stores the pointer to the next node in the linked list. A linked list node with no data is initialised with the integer `–1` . These nodes are linked together as an empty list. A pointer of `–1` identifies that node as the last node. The linked list can store 20 nodes. The global 2D array `LinkedList` stores the linked list. `LinkedList` is initialised as an empty list. The data in each node is initialised to `–1` . Each node’s pointer stores the index of the next node. The last node stores the pointer value `–1`, which indicates it is the last node. The global variable `FirstEmpty` stores the index of the first element in the empty list. This is the first node in the empty linked list when it is initialised, which is index `0` . The global variable `FirstNode` stores the index of the first element in the linked list. There is no data in the linked list when it is initialised, so `FirstNode` is initialised to `–1` . This diagram shows the content of the initialised array. ``` FirstEmpty = 0 FirstNode = –1 |Index|Data|Pointer| |---|---|---| |`0`|`-1`|`1`| |`1`|`-1`|`2`| |`2`|`-1`|`3`| |`3`|`-1`|`4`| |`4`|`-1`|`5`| |||| |`19`|<br>`-1`|<br>`-1`| ``` ### (a) Write program code for the main program to declare and initialise `LinkedList`, `FirstNode` and `FirstEmpty` . <span class="part-marks">2 marks</span> Save your program as **Question3_N24** . Copy and paste the program code into part **3(a)** in the evidence document. ### (b) The procedure `InsertData()` takes **five** positive integers as input from the user and inserts these into the linked list. <span class="part-marks">6 marks</span> Each data item is inserted at the front of the linked list. |The table shows the steps|to follow depending on the state of the linked list:| |---|---| |**Linked list state**|**Steps**| |not full|insert the data in the index pointed to by`FirstEmpty`<br>change the pointer to the index pointed to by`FirstNode`<br>change the values of`FirstNode` and`FirstEmpty`| |full|end the procedure| Any node that is at the end of the linked list has a pointer of `–1` . Write program code for `InsertData()` . Save your program. Copy and paste the program code into part **3(b)** in the evidence document. ### (c) The procedure `OutputLinkedList()` outputs the data in the linked list in order by following the pointers from `FirstNode` . #### (i) Write program code for `OutputLinkedList()` . <span class="part-marks">2 marks</span> Save your program. Copy and paste the program code into part **3(c)(i)** in the evidence document. #### (ii) Amend the main program to call `InsertData()` and then `OutputLinkedList()` . <span class="part-marks">1 mark</span> Save your program. Copy and paste the program code into part **3(c)(ii)** in the evidence document. #### (iii) Test your program with the test data: <span class="part-marks">1 mark</span> 5 1 2 3 8 Take a screenshot of the output. Save your program. Copy and paste the screenshot into part **3(c)(iii)** in the evidence document. ### (d) The procedure `RemoveData()` removes a node from the linked list. The procedure takes the data item to be removed from the linked list as a parameter. The procedure checks each node in the linked list, starting with the node `FirstNode`, until it finds the node to be removed. This node is added to the empty list, and pointers are changed as appropriate. The procedure only removes the first occurrence of the parameter. Assume that the data item being removed is in the linked list. #### (i) Write program code for `RemoveData()` . <span class="part-marks">5 marks</span> Save your program. Copy and paste the program code into part **3(d)(i)** in the evidence document. #### (ii) Amend the main program to: <span class="part-marks">1 mark</span> - call `RemoveData()` with the parameter 5 - output the word `"After"` - call `OutputLinkedList()` . Save your program. Copy and paste the program code into part **3(d)(ii)** in the evidence document. #### (iii) Test your program with both sets of given test data: <span class="part-marks">1 mark</span> Test data set 1: 5 6 8 9 5 Test data set 2: 10 7 8 5 6 Take a screenshot of each output. Save your program. Copy and paste the screenshot(s) into part **3(d)(iii)** in the evidence document.
Show mark scheme

3(a)

Python LinkedList = [] #global FirstNode = -1 FirstEmpty = 0 for x in range(0, 19): LinkedList.append([-1, x + 1]) LinkedList[19][0] = -1 LinkedList[19][1] = -1 Java private static Integer[][] LinkedList = new Integer[20][2]; private static Integer FirstNode; private static Integer FirstEmpty; public static void main(String args[]){ FirstNode = -1; FirstEmpty = 0; for(Integer X = 0; X < 19; X++){ LinkedList[X][0] = -1; LinkedList[X][1] = X + 1; } LinkedList[19][0] = -1; LinkedList[19][1] = -1; }

3(b)

Java public static void InsertData(){ Integer NewItem; Integer CurrentPointer = 0; Integer PreviousPointer = 0; Scanner scanner = new Scanner(System.in); Integer NextEmpty; for(Integer X = 0; X < 5; X++){ System.out.println("Enter the next number"); NewItem = Integer.parseInt(scanner.nextLine()); if(FirstEmpty == -1){ X = 5; }else{ NextEmpty = LinkedList[FirstEmpty][1]; LinkedList[FirstEmpty][0] = NewItem; LinkedList[FirstEmpty][1] = FirstNode; FirstNode = FirstEmpty; FirstEmpty = NextEmpty; } } }

3(c)(i)

Java public static void OutputLinkedList(){ Integer CurrentPointer = FirstNode; Boolean Flag = true; while(Flag){ System.out.println(LinkedList[CurrentPointer][0]); CurrentPointer = LinkedList[CurrentPointer][1]; if(CurrentPointer == -1){Flag = false;} } }

3(c)(ii) [1 mark]

1 mark for calling then InsertData() OutputLinkedList() Python InsertData() OutputLinkedList() VB.NET InsertData() OutputLinkedList() Java InsertData(); OutputLinkedList();

3(c)(iii) [1 mark]

1 mark for inputs of 5 1 2 3 8 and output of 8 3 2 1 5

3(d)(i)

Java public static void RemoveData(Integer ItemToRemove){ Integer CurrentPointer = 0; Integer PreviousNode = 0; Integer NewFirst = 0; if(LinkedList[FirstNode][0] == ItemToRemove){ NewFirst = LinkedList[FirstNode][1]; LinkedList[FirstNode][1] = FirstEmpty; FirstEmpty = FirstNode; FirstNode = NewFirst; }else{ if (FirstNode != -1){ CurrentPointer = FirstNode; PreviousNode = -1; while(ItemToRemove != LinkedList[CurrentPointer][0] && CurrentPointer != -1){ PreviousNode = CurrentPointer; CurrentPointer = LinkedList[CurrentPointer][1]; } if(ItemToRemove == LinkedList[CurrentPointer][0]){ LinkedList[PreviousNode][1] = LinkedList[CurrentPointer][1]; LinkedList[CurrentPointer][0] = -1; LinkedList[CurrentPointer][1] = FirstEmpty; FirstEmpty = CurrentPointer; } } } }

3(d)(ii)

Java public static void main(String args[]){ FirstNode = -1; FirstEmpty = 0; for(Integer X = 0; X < 20; X++){ LinkedList[X][0] = -1; LinkedList[X][1] = X + 1; } InsertData(); OutputLinkedList(); RemoveData(5); System.out.println("After"); OutputLinkedList(); }

3(d)(iii) [1 mark]

1 mark for input and output. Test data 1: Input 5 6 8 9 5 ‘After’ Output: 9 8 6 5 Test data 2: Input 10 7 8 5 6 “After” Output: 6 8 7 10

Q2
Oct/Nov 2024 Paper 4 v2

A linear queue data structure is designed using a record structure.

The record structure Queue has the following fields:

  • QueueArray, a 1D array of up to 100 integer values

  • Headpointer, a variable that stores the index of the first data item in QueueArray

  • Tailpointer, a variable that stores the index of the next free location in QueueArray .

(a) Write program code to declare the record structure Queue and its fields. 3 marks

If your programming language does not support record structures, a class can be declared instead.

If you are writing in Python, use comments to declare the appropriate data types.

Save your program as Question2_N24 .

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

(b) The main program creates a new Queue record with the identifier TheQueue . The head pointer is initialised to –1. The tail pointer is initialised to 0. Each element in the array is initialised with –1. 3 marks

Write program code for the main program.

Save your program.

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

(c) The pseudocode function Enqueue() inserts an integer value into the queue. 5 marks

The function is incomplete. There are three incomplete statements.

  FUNCTION Enqueue(BYREF AQueue : Queue, BYVAL TheData : INTEGER)
  RETURNS INTEGER
IF AQueue.Headpointer = -1 THEN

AQueue.QueueArray[AQueue.Tailpointer]

AQueue.Headpointer  0
# ←
AQueue.Tailpointer  AQueue.Tailpointer + 1
# ←
RETURN 1
ELSE

IF AQueue.Tailpointer > ______ THEN

RETURN -1
ELSE
AQueue.QueueArray[AQueue.Tailpointer]  TheData
# ←

AQueue.Tailpointer AQueue.Tailpointer

RETURN 1
    ENDIF
    ENDIF
    ENDFUNCTION

Write program code for Enqueue() .

Save your program.

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

(d) The function ReturnAllData() accesses TheQueue . It concatenates all the integer values that have been inserted into the queue’s array, starting from the value stored at HeadPointer, with a space between each integer value. The string of concatenated values is returned. 3 marks

None of the integer values are removed from the queue.

Write program code for ReturnAllData() .

Save your program.

Copy and paste the program code into part 2(d) in the evidence document. (e) (i) The main program asks the user to enter 10 integers with values of 0 or greater. It reads 5 marks each input repeatedly until a valid number is entered.

All 10 valid inputs are added to the queue, using Enqueue() .

If the value returned from Enqueue() is –1, a message is output to state that the queue is full, otherwise a message is output to state that the item has been added to the queue.

The function ReturnAllData() is called once all 10 integers have been entered and the return value from the function call is output.

Amend the main program to perform these actions.

Save your program.

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

(ii) Test your program with the following inputs in the order given: 2 marks

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

Take a screenshot of the output.

Save your program.

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

(f) The function Dequeue() accesses TheQueue . The function returns –1 if the queue is empty. 4 marks

If the queue is not empty, the function returns the next item in the queue and updates the relevant pointer(s).

The data is not replaced or deleted from the queue.

Write program code for Dequeue() .

Save your program.

Copy and paste the program code into part 2(f) in the evidence document. (g) (i) The main program calls Dequeue() twice, and each time it either outputs ‘Queue empty’ 3 marks if there is no data in the queue or outputs the return value.

The main program then calls ReturnAllData() a second time.

Amend the main program.

Save your program.

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

(ii) Test your program with the following inputs in the order given: 1 mark

10 9 8 7 6 5 4 3 2 1

Take a screenshot of the output.

Save your program.

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

A linear queue data structure is designed using a record structure. The record structure `Queue` has the following fields: - `QueueArray`, a 1D array of up to 100 integer values - `Headpointer`, a variable that stores the index of the first data item in `QueueArray` - `Tailpointer`, a variable that stores the index of the next free location in `QueueArray` . ### (a) Write program code to declare the record structure `Queue` and its fields. <span class="part-marks">3 marks</span> If your programming language does **not** support record structures, a class can be declared instead. If you are writing in Python, use comments to declare the appropriate data types. Save your program as **Question2_N24** . Copy and paste the program code into part **2(a)** in the evidence document. ### (b) The main program creates a new `Queue` record with the identifier `TheQueue` . The head pointer is initialised to –1. The tail pointer is initialised to 0. Each element in the array is initialised with –1. <span class="part-marks">3 marks</span> Write program code for the main program. Save your program. Copy and paste the program code into part **2(b)** in the evidence document. ### (c) The pseudocode function `Enqueue()` inserts an integer value into the queue. <span class="part-marks">5 marks</span> The function is incomplete. There are **three** incomplete statements. ``` FUNCTION Enqueue(BYREF AQueue : Queue, BYVAL TheData : INTEGER) RETURNS INTEGER ``` ``` IF AQueue.Headpointer = -1 THEN ``` `AQueue.QueueArray[AQueue.Tailpointer]` # ← ``` AQueue.Headpointer 0 # ← ``` ``` AQueue.Tailpointer AQueue.Tailpointer + 1 # ← ``` ``` RETURN 1 ``` ``` ELSE ``` `IF AQueue.Tailpointer >` ______ `THEN` ``` RETURN -1 ``` ``` ELSE ``` ``` AQueue.QueueArray[AQueue.Tailpointer] TheData # ← ``` `AQueue.Tailpointer` `AQueue.Tailpointer` # ← ``` RETURN 1 ``` ``` ENDIF ENDIF ENDFUNCTION ``` Write program code for `Enqueue()` . Save your program. Copy and paste the program code into part **2(c)** in the evidence document. ### (d) The function `ReturnAllData()` accesses `TheQueue` . It concatenates all the integer values that have been inserted into the queue’s array, starting from the value stored at `HeadPointer`, with a space between each integer value. The string of concatenated values is returned. <span class="part-marks">3 marks</span> None of the integer values are removed from the queue. Write program code for `ReturnAllData()` . Save your program. Copy and paste the program code into part **2(d)** in the evidence document. **(e) (i)** The main program asks the user to enter 10 integers with values of 0 or greater. It reads <span class="part-marks">5 marks</span> each input repeatedly until a valid number is entered. All 10 valid inputs are added to the queue, using `Enqueue()` . If the value returned from `Enqueue()` is –1, a message is output to state that the queue is full, otherwise a message is output to state that the item has been added to the queue. The function `ReturnAllData()` is called once all 10 integers have been entered and the return value from the function call is output. Amend the main program to perform these actions. Save your program. Copy and paste the program code into part **2(e)(i)** in the evidence document. #### (ii) Test your program with the following inputs in the order given: <span class="part-marks">2 marks</span> 10 9 –1 8 7 6 5 4 3 2 1 Take a screenshot of the output. Save your program. Copy and paste the screenshot into part **2(e)(ii)** in the evidence document. ### (f) The function `Dequeue()` accesses `TheQueue` . The function returns –1 if the queue is empty. <span class="part-marks">4 marks</span> If the queue is **not** empty, the function returns the next item in the queue and updates the relevant pointer(s). The data is **not** replaced or deleted from the queue. Write program code for `Dequeue()` . Save your program. Copy and paste the program code into part **2(f)** in the evidence document. **(g) (i)** The main program calls `Dequeue()` twice, and each time it either outputs ‘Queue empty’ <span class="part-marks">3 marks</span> if there is no data in the queue or outputs the return value. The main program then calls `ReturnAllData()` a second time. Amend the main program. Save your program. Copy and paste the program code into part **2(g)(i)** in the evidence document. #### (ii) Test your program with the following inputs in the order given: <span class="part-marks">1 mark</span> 10 9 8 7 6 5 4 3 2 1 Take a screenshot of the output. Save your program. Copy and paste the screenshot into part **2(g)(ii)** in the evidence document.
Show mark scheme

2(a) [3 marks]

1 mark each to max • Record structure or class with constructor (and end where appropriate) … Queue • … containing a 1D array of (100) integers QueueArray • … containing and as integers HeadPointer TailPointer e.g. Python class Queue: def init(self): self.QueueArray = [] HeadPointer = 0 #integer TailPointer = 0 #integer for x in range(0, 100): self.QueueArray.append(-1) VB.NET Structure Queue Dim QueueArray() As Integer Dim HeadPointer As Integer Dim TailPointer As Integer End Structure Java class queue{ private static Integer[] QueueArray = new Integer[100]; private static Integer HeadPointer; private static Integer TailPointer; public queue(){ } }

2(b)

HeadPointer = -1; TailPointer = 0; for(Integer x = 0; x < 100; x++){ QueueArray[x] = -1; } } } public static void main(String args[]){ queue TheQueue = new queue(); }

2(c)

Java public static Integer Enqueue(Integer TheData){ if(GetHeadPointer() == -1){ SetData(TheData); SetHeadPointer(0); SetTailPointer(GetTailPointer() + 1); return 1; }else if(GetTailPointer() > 99){ return -1; }else{ SetData(TheData); SetTailPointer(GetTailPointer() + 1); return 1; } }

2(d)

VB.NET Function ReturnAllData(AQueue As Queue) Dim Temp As String = "" For X = AQueue.HeadPointer To AQueue.TailPointer - 1 Temp = Temp & AQueue.QueueArray(X).ToString() & " " Next X Return Temp End Function Java public static String ReturnAllData(){ String Temp = ""; Integer Counter = 0; for(int X = HeadPointer; X < TailPointer; X++){ Temp = Temp + Integer.toString(QueueArray[X]) + " "; } return Temp; }

2(e)(i)

End While ReturnValue = Enqueue(TheQueue, DataInput) If ReturnValue = 2 Then Console.WriteLine("Queue full") Else Console.WriteLine("Item inserted") End If Next Console.WriteLine(ReturnAllData(TheQueue)) Java Boolean Continue = true; Integer DataInput = -1; Scanner scanner = new Scanner(System.in); Integer ReturnValue; for(Integer x = 0; x < 10; x++){ Continue = true; while(Continue == true){ System.out.println("Enter an integer that is 0 or more"); DataInput = Integer.parseInt(scanner.nextLine()); if(DataInput > -1){ Continue = false; } } ReturnValue = Enqueue(DataInput); if(ReturnValue == -1){ System.out.println("Queue full"); }else{ System.out.println("Item inserted"); } } System.out.println(ReturnAllData());

2(e)(ii) [2 marks]

1 mark for each • All values input and 10 messages ‘Inserted’ (i.e. –1 is not inserted) • Screenshot show 10 9 8 7 6 5 4 3 2 1 on one line with a space between each number e.g.

2(f)

VB.NET Function Dequeue(ByRef AQueue As Queue) If AQueue.HeadPointer = 100 or AQueue.HeadPointer = -1 or AQueue.HeadPointer = AQueue.TailPointer Then Return -1 Else Dim Temp As Integer = AQueue.QueueArray(AQueue.HeadPointer) AQueue.HeadPointer += 1 Return Temp End If End Function Java public static Integer Dequeue(){ if(GetHeadPointer() = 100 || GetTailpointer() == -1 || GetHeadPointer() == GetTailpointer()){ return -1; }else{ Integer Temp = GetData(GetHeadPointer()); SetHeadPointer(GetHeadPointer() + 1); return Temp; } }

2(g)(i)

If ReturnValue = -1 Then Console.WriteLine("Queue empty") Else Console.WriteLine(ReturnValue, " is returned") End If Console.WriteLine(ReturnAllData(TheQueue)) Java ReturnValue = Dequeue(); if(ReturnValue == -1){ System.out.println("Queue empty"); }else{ System.out.println(ReturnValue + " is returned"); } ReturnValue = Dequeue(); if(ReturnValue == -1){ System.out.println("Queue empty"); }else{ System.out.println(ReturnValue + " is returned"); } ReturnAllData(TheQueue);

2(g)(ii) [1 mark]

1 mark each • Screenshot shows the input of 10 9 8 7 6 5 4 3 2 1 Output for 10 returned Output for 9 is returned e.g.

Q3
Oct/Nov 2024 Paper 4 v2

The text file HighScoreTable.txt stores the top seven player scores for a game.

The data in the file is stored in the order:

Player ID

Game level

Score

Each item of data is stored on a new line. For example, the first set of data in the file is:

Player ID: GHEH

Game level: 3

Score: 10

(a) The data about the players and their scores is stored in a 2D array of strings with the identifier HighScores . 2 marks

The first dimension of the array has seven elements: one for each player. The second dimension of the array has three elements: one for the player ID, one for the game level and one for the score. All data is stored in the array as strings.

HighScores is declared local to the main program, and all elements are initialised to an empty string, for example " " .

Write program code to declare and initialise HighScores .

Save your program as Question3_N24 .

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

(b) The function ReadData() reads the data from HighScoreTable.txt and stores the data in a 2D array. The function returns the 2D array. 5 marks

The function uses exception handling when opening and reading data from the file.

Write program code for ReadData() .

Save your program.

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

(c) The procedure OutputHighScores() takes a 2D array as a parameter. It outputs each player’s ID, level and score in the order they are in the array. The outputs are in the format: 2 marks

GHEH reached level 3 with a score of 10

Write program code for OutputHighScores() .

Save your program.

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

(d) The scores in HighScoreTable.txt are not in order. 4 marks

The player scores are first sorted by the game level they reached. For example, all players that reached level 5 are higher in the high score table than players that reached level 4.

The players that reached the same level are then sorted in descending order of score.

An example sorted high score table is:

Position Player ID Game level Score
1 GFED 5 25
2 HJKM 4 21
3 RERR 4 19
4 TTYU 4 15
5 WSVG 3 20
6 PPTR 3 15
7 SNQT 2 10

The function SortScores() uses a bubble sort to sort the data as described and returns the sorted array.

Write program code for SortScores() .

Save your program.

Copy and paste the program code into part 3(d) in the evidence document. (e) (i) Amend the main program to implement these steps in the order given: 2 marks

  • call ReadData() and store the returned array in HighScores

  • output "Before"

  • call OutputHighScores() with HighScores as a parameter

  • call SortScores() and store the returned array in HighScores

  • output "After"

  • call OutputHighScores() with HighScores 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 Take a screenshot of the output. 2 marks

Save your program.

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

The text file `HighScoreTable.txt` stores the top seven player scores for a game. The data in the file is stored in the order: Player ID Game level Score Each item of data is stored on a new line. For example, the first set of data in the file is: Player ID: GHEH Game level: 3 Score: 10 ### (a) The data about the players and their scores is stored in a 2D array of strings with the identifier `HighScores` . <span class="part-marks">2 marks</span> The first dimension of the array has seven elements: one for each player. The second dimension of the array has three elements: one for the player ID, one for the game level and one for the score. All data is stored in the array as strings. `HighScores` is declared local to the main program, and all elements are initialised to an empty string, for example `" "` . Write program code to declare and initialise `HighScores` . Save your program as **Question3_N24** . Copy and paste the program code into part **3(a)** in the evidence document. ### (b) The function `ReadData()` reads the data from `HighScoreTable.txt` and stores the data in a 2D array. The function returns the 2D array. <span class="part-marks">5 marks</span> The function uses exception handling when opening and reading data from the file. Write program code for `ReadData()` . Save your program. Copy and paste the program code into part **3(b)** in the evidence document. ### (c) The procedure `OutputHighScores()` takes a 2D array as a parameter. It outputs each player’s ID, level and score in the order they are in the array. The outputs are in the format: <span class="part-marks">2 marks</span> GHEH reached level 3 with a score of 10 Write program code for `OutputHighScores()` . Save your program. Copy and paste the program code into part **3(c)** in the evidence document. ### (d) The scores in `HighScoreTable.txt` are **not** in order. <span class="part-marks">4 marks</span> The player scores are first sorted by the game level they reached. For example, all players that reached level 5 are higher in the high score table than players that reached level 4. The players that reached the same level are then sorted in descending order of score. An example sorted high score table is: |Position|Player ID|Game level|Score| |---|---|---|---| |1|GFED|5|25| |2|HJKM|4|21| |3|RERR|4|19| |4|TTYU|4|15| |5|WSVG|3|20| |6|PPTR|3|15| |7|SNQT|2|10| The function `SortScores()` uses a bubble sort to sort the data as described and returns the sorted array. Write program code for `SortScores()` . Save your program. Copy and paste the program code into part **3(d)** in the evidence document. **(e) (i)** Amend the main program to implement these steps in the order given: <span class="part-marks">2 marks</span> - call `ReadData()` and store the returned array in `HighScores` - output `"Before"` - call `OutputHighScores()` with `HighScores` as a parameter - call `SortScores()` and store the returned array in `HighScores` - output `"After"` - call `OutputHighScores()` with `HighScores` 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 Take a screenshot of the output. <span class="part-marks">2 marks</span> Save your program. Copy and paste the screenshot into part **3(e)(ii)** in the evidence document.
Show mark scheme

3(a) [2 marks]

1 mark each •  created as 2D array, (of strings) with (min) 7 3 elements (local to main) … HighScores • … all elements initialised to empty string ( ) "" e.g. Python HighScores = [] #String, 7 x 3 HighScores = [['' for x in range(3)] for y in range(7)] VB.NET Dim HighScores(7, 3) As String For(X = 0 to 7) For(Y = 0 to 3) HighScores(X, Y) = "" Next Y Next X Java String[][] HighScores = new String[7][3]; for(Int X = 0; X <7; X++){ for(Int Y = 0; Y < 3; Y++){ HighScores[X][Y] = ""; } }

3(b)

HighScores[X][1] = Reader.readLine(); HighScores[X][2] = Reader.readLine(); }catch(IOException ex){} } try{ Reader.close(); }catch(IOException ex){} return HighScores; }catch(FileNotFoundException e){ System.out.println("File not found"); } return HighScores; }

3(c)

Java public static void OutputHighScores(String[][] HighScores){ for(Integer x = 0; x < 7; x++){ System.out.println(HighScores[x][0] + " reached level " + HighScores[x][1] + " with a score of " + HighScores[x][2]); } }

3(d)

} return HighScores; }

3(e)(i)

Java public static void main(String args[]){ String[][] HighScores = new String[7][3]; HighScores = ReadData(); System.out.println("Before"); OutputHighScores(HighScores); HighScores = SortScores(HighScores); System.out.println("After"); OutputHighScores(HighScores); }

3(e)(ii) [2 marks]

Output showing ‘Before’ and players and scores in correct format before sorting Output showing ‘After’ players and scores in correct order and format after sorting e.g.

Q1
Oct/Nov 2024 Paper 4 v3

A program sorts string data using different sorting methods.

(a) The text file Data.txt stores string data items. Each data item is on a new line in the text file. 6 marks

The function ReadData() :

  • has a local array of strings that can store 45 items

  • reads each line of data and stores it in the array

  • returns the array.

Write program code for the function ReadData() .

Save your program as Question1_N24 .

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

A program sorts string data using different sorting methods. ### (a) The text file `Data.txt` stores string data items. Each data item is on a new line in the text file. <span class="part-marks">6 marks</span> The function `ReadData()` : - has a local array of strings that can store 45 items - reads each line of data and stores it in the array - returns the array. Write program code for the function `ReadData()` . Save your program as **Question1_N24** . Copy and paste the program code into part **1(a)** in the evidence document.
Show mark scheme

1(a)

FileReader.Close() Catch ex As Exception Console.WriteLine("No file found") End Try Return Colours End Function Java public static String[] ReadData(){ String TextFile = "Data.txt"; String Colours[] = new String[45]; try{ FileReader f = new FileReader(TextFile); BufferedReader Reader = new BufferedReader(f); for(Integer X = 0; X < 45; X++){ try{ Colours[X] = Reader.readLine(); }catch(IOException ex){} } try{ Reader.close(); }catch(IOException ex){} return Colours; }catch(FileNotFoundException e){ System.out.println("File not found"); } return Colours; }

1(b)(i) [2 marks]

1 mark each • Function header (and end where appropriate) taking (min) one parameter • Looping through each parameter array element, concatenating with space and returning Python def FormatArray(DataArray): OutputText = "" for x in range(0, 45): OutputText = OutputText + DataArray[x] + " " return OutputText VB.NET Function FormatArray(DataArray) Dim OutputText As String = "" For X = 0 To 44 OutputText = OutputText & DataArray(X) & " " Next Return OutputText End Function Java public static String FormatArray(String[] DataArray){ String OutputText = ""; for(Integer X = 0; X < 45; X++){ OutputText = OutputText + DataArray[X] + " "; } return OutputText; }

1(b)(ii) [3 marks]

1 mark each: • Calling and storing returned array … ReadData() • … calling with returned array FormatArray() • Outputting return value from FormatArray() Python Colours = ReadData() #string array print(FormatArray(Colours)) VB.NET Dim Colours(45) As String Colours = ReadData() Console.WriteLine(FormatArray(Colours)) Java String[] Colours = new String[45]; Colours = ReadData(); System.out.println(FormatArray(Colours));

1(b)(iii) [1 mark]

1 mark for output showing all colours in one string e.g.

1(c)

Java public static Integer CompareStrings(String First, String Second){ Integer Count = 0; while(true){ if(First.substring(Count, Count + 1).compareTo(Second.substring(Count, Count + 1)) < 0){ return 1; }else if(First.substring(Count, Count + 1).compareTo(Second.substring(Count, Count + 1))>0){ return 2; }else{ Count++; } } }

1(d)(i)

Temp = DataArray[Y]; DataArray[Y] = DataArray[Y+1]; DataArray[Y+1] = Temp; } } } return DataArray; }

1(d)(ii) [2 marks]

1 mark each • Calling with array as parameter and using/storing return value Bubble() • Calling with return value from and outputting return value FormatArray() Bubble() Python BubbleSorted = Bubble(Colours) print(FormatArray(BubbleSorted)) VB.NET Dim BubbleSorted(45) As String BubbleSorted = Bubble(Colours) Console.WriteLine(FormatArray(BubbleSorted)) Java String[] BubbleSorted = new String[45]; BubbleSorted = Bubble(Colours); System.out.println(FormatArray(BubbleSorted));

1(d)(iii) [1 mark]

1 mark for sorted data e.g.

Q3
Oct/Nov 2024 Paper 4 v3

A linked list stores positive integer data in a 2D array. The first dimension of the array stores the integer data. The second dimension of the array stores the pointer to the next node in the linked list.

A linked list node with no data is initialised with the integer –1 . These nodes are linked together as an empty list. A pointer of –1 identifies that node as the last node.

The linked list can store 20 nodes.

The global 2D array LinkedList stores the linked list.

LinkedList is initialised as an empty list. The data in each node is initialised to –1 . Each node’s pointer stores the index of the next node. The last node stores the pointer value –1, which indicates it is the last node.

The global variable FirstEmpty stores the index of the first element in the empty list. This is the first node in the empty linked list when it is initialised, which is index 0 .

The global variable FirstNode stores the index of the first element in the linked list. There is no data in the linked list when it is initialised, so FirstNode is initialised to –1 .

This diagram shows the content of the initialised array.

  FirstEmpty = 0
  FirstNode = –1

|Index|Data|Pointer|
|---|---|---|
|`0`|`-1`|`1`|
|`1`|`-1`|`2`|
|`2`|`-1`|`3`|
|`3`|`-1`|`4`|
|`4`|`-1`|`5`|
||||
|`19`|<br>`-1`|<br>`-1`|

(a) Write program code for the main program to declare and initialise LinkedList, FirstNode and FirstEmpty . 2 marks

Save your program as Question3_N24 .

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

(b) The procedure InsertData() takes five positive integers as input from the user and inserts these into the linked list. 6 marks

Each data item is inserted at the front of the linked list.

The table shows the steps to follow depending on the state of the linked list:
Linked list state Steps
not full insert the data in the index pointed to byFirstEmpty
change the pointer to the index pointed to byFirstNode
change the values ofFirstNode andFirstEmpty
full end the procedure

Any node that is at the end of the linked list has a pointer of –1 .

Write program code for InsertData() .

Save your program.

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

(c) The procedure OutputLinkedList() outputs the data in the linked list in order by following the pointers from FirstNode .

(i) Write program code for OutputLinkedList() . 2 marks

Save your program.

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

(ii) Amend the main program to call InsertData() and then OutputLinkedList() . 1 mark

Save your program.

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

(iii) Test your program with the test data: 1 mark

5 1 2 3 8

Take a screenshot of the output.

Save your program.

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

(d) The procedure RemoveData() removes a node from the linked list.

The procedure takes the data item to be removed from the linked list as a parameter.

The procedure checks each node in the linked list, starting with the node FirstNode, until it finds the node to be removed. This node is added to the empty list, and pointers are changed as appropriate. The procedure only removes the first occurrence of the parameter.

Assume that the data item being removed is in the linked list.

(i) Write program code for RemoveData() . 5 marks

Save your program.

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

(ii) Amend the main program to: 1 mark

  • call RemoveData() with the parameter 5

  • output the word "After"

  • call OutputLinkedList() .

Save your program.

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

(iii) Test your program with both sets of given test data: 1 mark

Test data set 1: 5 6 8 9 5

Test data set 2: 10 7 8 5 6

Take a screenshot of each output.

Save your program.

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

A linked list stores positive integer data in a 2D array. The first dimension of the array stores the integer data. The second dimension of the array stores the pointer to the next node in the linked list. A linked list node with no data is initialised with the integer `–1` . These nodes are linked together as an empty list. A pointer of `–1` identifies that node as the last node. The linked list can store 20 nodes. The global 2D array `LinkedList` stores the linked list. `LinkedList` is initialised as an empty list. The data in each node is initialised to `–1` . Each node’s pointer stores the index of the next node. The last node stores the pointer value `–1`, which indicates it is the last node. The global variable `FirstEmpty` stores the index of the first element in the empty list. This is the first node in the empty linked list when it is initialised, which is index `0` . The global variable `FirstNode` stores the index of the first element in the linked list. There is no data in the linked list when it is initialised, so `FirstNode` is initialised to `–1` . This diagram shows the content of the initialised array. ``` FirstEmpty = 0 FirstNode = –1 |Index|Data|Pointer| |---|---|---| |`0`|`-1`|`1`| |`1`|`-1`|`2`| |`2`|`-1`|`3`| |`3`|`-1`|`4`| |`4`|`-1`|`5`| |||| |`19`|<br>`-1`|<br>`-1`| ``` ### (a) Write program code for the main program to declare and initialise `LinkedList`, `FirstNode` and `FirstEmpty` . <span class="part-marks">2 marks</span> Save your program as **Question3_N24** . Copy and paste the program code into part **3(a)** in the evidence document. ### (b) The procedure `InsertData()` takes **five** positive integers as input from the user and inserts these into the linked list. <span class="part-marks">6 marks</span> Each data item is inserted at the front of the linked list. |The table shows the steps|to follow depending on the state of the linked list:| |---|---| |**Linked list state**|**Steps**| |not full|insert the data in the index pointed to by`FirstEmpty`<br>change the pointer to the index pointed to by`FirstNode`<br>change the values of`FirstNode` and`FirstEmpty`| |full|end the procedure| Any node that is at the end of the linked list has a pointer of `–1` . Write program code for `InsertData()` . Save your program. Copy and paste the program code into part **3(b)** in the evidence document. ### (c) The procedure `OutputLinkedList()` outputs the data in the linked list in order by following the pointers from `FirstNode` . #### (i) Write program code for `OutputLinkedList()` . <span class="part-marks">2 marks</span> Save your program. Copy and paste the program code into part **3(c)(i)** in the evidence document. #### (ii) Amend the main program to call `InsertData()` and then `OutputLinkedList()` . <span class="part-marks">1 mark</span> Save your program. Copy and paste the program code into part **3(c)(ii)** in the evidence document. #### (iii) Test your program with the test data: <span class="part-marks">1 mark</span> 5 1 2 3 8 Take a screenshot of the output. Save your program. Copy and paste the screenshot into part **3(c)(iii)** in the evidence document. ### (d) The procedure `RemoveData()` removes a node from the linked list. The procedure takes the data item to be removed from the linked list as a parameter. The procedure checks each node in the linked list, starting with the node `FirstNode`, until it finds the node to be removed. This node is added to the empty list, and pointers are changed as appropriate. The procedure only removes the first occurrence of the parameter. Assume that the data item being removed is in the linked list. #### (i) Write program code for `RemoveData()` . <span class="part-marks">5 marks</span> Save your program. Copy and paste the program code into part **3(d)(i)** in the evidence document. #### (ii) Amend the main program to: <span class="part-marks">1 mark</span> - call `RemoveData()` with the parameter 5 - output the word `"After"` - call `OutputLinkedList()` . Save your program. Copy and paste the program code into part **3(d)(ii)** in the evidence document. #### (iii) Test your program with both sets of given test data: <span class="part-marks">1 mark</span> Test data set 1: 5 6 8 9 5 Test data set 2: 10 7 8 5 6 Take a screenshot of each output. Save your program. Copy and paste the screenshot(s) into part **3(d)(iii)** in the evidence document.
Show mark scheme

3(a)

Python LinkedList = [] #global FirstNode = -1 FirstEmpty = 0 for x in range(0, 19): LinkedList.append([-1, x + 1]) LinkedList[19][0] = -1 LinkedList[19][1] = -1 Java private static Integer[][] LinkedList = new Integer[20][2]; private static Integer FirstNode; private static Integer FirstEmpty; public static void main(String args[]){ FirstNode = -1; FirstEmpty = 0; for(Integer X = 0; X < 19; X++){ LinkedList[X][0] = -1; LinkedList[X][1] = X + 1; } LinkedList[19][0] = -1; LinkedList[19][1] = -1; }

3(b)

Java public static void InsertData(){ Integer NewItem; Integer CurrentPointer = 0; Integer PreviousPointer = 0; Scanner scanner = new Scanner(System.in); Integer NextEmpty; for(Integer X = 0; X < 5; X++){ System.out.println("Enter the next number"); NewItem = Integer.parseInt(scanner.nextLine()); if(FirstEmpty == -1){ X = 5; }else{ NextEmpty = LinkedList[FirstEmpty][1]; LinkedList[FirstEmpty][0] = NewItem; LinkedList[FirstEmpty][1] = FirstNode; FirstNode = FirstEmpty; FirstEmpty = NextEmpty; } } }

3(c)(i)

Java public static void OutputLinkedList(){ Integer CurrentPointer = FirstNode; Boolean Flag = true; while(Flag){ System.out.println(LinkedList[CurrentPointer][0]); CurrentPointer = LinkedList[CurrentPointer][1]; if(CurrentPointer == -1){Flag = false;} } }

3(c)(ii) [1 mark]

1 mark for calling then InsertData() OutputLinkedList() Python InsertData() OutputLinkedList() VB.NET InsertData() OutputLinkedList() Java InsertData(); OutputLinkedList();

3(c)(iii) [1 mark]

1 mark for inputs of 5 1 2 3 8 and output of 8 3 2 1 5

3(d)(i)

Java public static void RemoveData(Integer ItemToRemove){ Integer CurrentPointer = 0; Integer PreviousNode = 0; Integer NewFirst = 0; if(LinkedList[FirstNode][0] == ItemToRemove){ NewFirst = LinkedList[FirstNode][1]; LinkedList[FirstNode][1] = FirstEmpty; FirstEmpty = FirstNode; FirstNode = NewFirst; }else{ if (FirstNode != -1){ CurrentPointer = FirstNode; PreviousNode = -1; while(ItemToRemove != LinkedList[CurrentPointer][0] && CurrentPointer != -1){ PreviousNode = CurrentPointer; CurrentPointer = LinkedList[CurrentPointer][1]; } if(ItemToRemove == LinkedList[CurrentPointer][0]){ LinkedList[PreviousNode][1] = LinkedList[CurrentPointer][1]; LinkedList[CurrentPointer][0] = -1; LinkedList[CurrentPointer][1] = FirstEmpty; FirstEmpty = CurrentPointer; } } } }

3(d)(ii)

Java public static void main(String args[]){ FirstNode = -1; FirstEmpty = 0; for(Integer X = 0; X < 20; X++){ LinkedList[X][0] = -1; LinkedList[X][1] = X + 1; } InsertData(); OutputLinkedList(); RemoveData(5); System.out.println("After"); OutputLinkedList(); }

3(d)(iii) [1 mark]

1 mark for input and output. Test data 1: Input 5 6 8 9 5 ‘After’ Output: 9 8 6 5 Test data 2: Input 10 7 8 5 6 “After” Output: 6 8 7 10

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)

Q1
May/Jun 2024 Paper 4 v2

A program outputs a main word. The program asks the user to enter the different words of 3 or more letters that can be made from the letters in the main word. These are called the answers.

There are 3 files: Easy.txt, Medium.txt and Hard.txt . Each file has the main word on the first line. For example, the main word in Easy.txt is house.

The answers are stored in the file. Each answer is on a new line after the main word. For example, Easy.txt has 14 answers that can be made from the letters in house.

The words read from the text file are stored in the global array WordArray . The number of words that can be made from the letters in the main word is stored in the global variable NumberWords .

(a) The procedure ReadWords() : 6 marks

  • takes a file name as a parameter

  • opens the file and reads in the data

  • stores the main word in the first element in WordArray

  • stores each answer in a new element in WordArray

  • counts and stores the number of answers.

Write program code for the procedure ReadWords() .

Save your program as Question1_J24 .

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

(b) The main program asks the user to enter "easy", "medium" or "hard" and calls ReadWords() with the filename that matches the user’s input. For example, if the user enters "easy", the parameter is "Easy.txt" . 4 marks

Write program code for the main program.

Save your program.

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

A program outputs a main word. The program asks the user to enter the different words of 3 or more letters that can be made from the letters in the main word. These are called the answers. There are 3 files: `Easy.txt`, `Medium.txt` and `Hard.txt` . Each file has the main word on the first line. For example, the main word in `Easy.txt` is house. The answers are stored in the file. Each answer is on a new line after the main word. For example, `Easy.txt` has 14 answers that can be made from the letters in house. The words read from the text file are stored in the global array `WordArray` . The number of words that can be made from the letters in the main word is stored in the global variable `NumberWords` . ### (a) The procedure `ReadWords()` : <span class="part-marks">6 marks</span> - takes a file name as a parameter - opens the file and reads in the data - stores the main word in the first element in `WordArray` - stores each answer in a new element in `WordArray` - counts and stores the number of answers. Write program code for the procedure `ReadWords()` . Save your program as **Question1_J24** . Copy and paste the program code into part **1(a)** in the evidence document. ### (b) The main program asks the user to enter `"easy"`, `"medium"` or `"hard"` and calls `ReadWords()` with the filename that matches the user’s input. For example, if the user enters `"easy"`, the parameter is `"Easy.txt"` . <span class="part-marks">4 marks</span> Write program code for the main program. Save your program. Copy and paste the program code into part **1(b)** in the evidence document.
Show mark scheme

1(a)

}catch(FileNotFoundException e){ System.out.println("File not found"); VB.NET Sub ReadWords(FileName As String) Try Dim DataReader As StreamReader = New StreamReader(FileName) NumberWords = 0 Do Until DataReader.EndOfStream WordArray(NumberWords) = DataReader.ReadLine() NumberWords = NumberWords + 1 Loop DataReader.Close() Catch ex As Exception Console.WriteLine("Invalid file") End Try End Sub Python def ReadWords(FileName): global WordArray global NumberWords File = open(FileName, 'r') DataRead = File.read().strip() File.close() WordArray = DataRead.split() NumberWords = len(WordArray)

1(b)

FileName = "Hard.txt" End If ReadWords(FileName) End Sub Python WordArray = [] NumberWords = 0 Choice = input("Easy, medium or hard? ").lower() if Choice == "easy": File = "Easy.txt" elif Choice == "medium": File = "Medium.txt" else: File = "Hard.txt" ReadWords(File)

1(c)(i)

for x in range(0, NumberWords): WordArray[x] = "" QuantityFound = QuantityFound + 1 print("Correct, you have found", QuantityFound, "words") Found = True if Found == False: print("Sorry that was incorrect")

1(c)(ii)

if Correct < 100: print("The words you missed are") for x in range(0, NumberWords-1): if WordArray[x] != "": print(WordArray[x])

1(d)(i)

VB.NET Sub ReadWords(FileName As String) Try Dim DataReader As StreamReader = New StreamReader(FileName) NumberWords = 0 Do Until DataReader.EndOfStream WordArray(NumberWords) = DataReader.ReadLine() NumberWords = NumberWords + 1 Loop DataReader.Close() Play() Catch ex As Exception Console.WriteLine("Invalid file") End Try End Sub Python def ReadWords(FileName): global WordArray global NumberWords File = open(FileName, 'r') DataRead = File.read().strip() File.close() WordArray = DataRead.split() NumberWords = len(WordArray) Play()

1(d)(ii) [1 mark]

1 mark for screenshot showing the inputs "easy", "she", "out", "no" e.g.

1(d)(iii) [1 mark]

1 mark for screenshot showing the inputs ‘hard’, ‘fine’, ‘fined’, ‘idea’, ‘no’ 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)

Q8
Oct/Nov 2023 Paper 3 v1

(a) A pseudocode algorithm finds a customer account record in a random file and outputs it. The records are stored using the user-defined data type TAccount . 5 marks

    TYPE TAccount
    DECLARE AccountNumber : INTEGER
    DECLARE LastName : STRING
    DECLARE FirstName : STRING
    DECLARE Address : STRING
    DECLARE ContactNumber : STRING
    ENDTYPE

Complete the file handling pseudocode.

The function Hash() takes the customer account number as a parameter, calculates and returns the hash value.

    DECLARE Customer : TAccount
    DECLARE Location : INTEGER
    DECLARE AccountFile : STRING

______ "AccountRecords.dat"

______ AccountFile

    OUTPUT "Please enter an account number"
    INPUT Customer.AccountNumber

Location Hash( ______)

SEEK ______, Location

______ AccountFile,

    OUTPUT Customer       // output customer record
    CLOSEFILE AccountFile

(b) Define the term exception handling . 1 mark

(c) State two possible causes of an exception. 2 marks

### (a) A pseudocode algorithm finds a customer account record in a random file and outputs it. The records are stored using the user-defined data type `TAccount` . <span class="part-marks">5 marks</span> ``` TYPE TAccount DECLARE AccountNumber : INTEGER DECLARE LastName : STRING DECLARE FirstName : STRING DECLARE Address : STRING DECLARE ContactNumber : STRING ENDTYPE ``` Complete the file handling pseudocode. The function `Hash()` takes the customer account number as a parameter, calculates and returns the hash value. ``` DECLARE Customer : TAccount DECLARE Location : INTEGER DECLARE AccountFile : STRING ``` ______ `"AccountRecords.dat"` ______ `AccountFile` ``` OUTPUT "Please enter an account number" INPUT Customer.AccountNumber ``` `Location` `Hash(` ______) `SEEK` ______, `Location` ______ `AccountFile,` ``` OUTPUT Customer // output customer record CLOSEFILE AccountFile ``` ### (b) Define the term **exception handling** . <span class="part-marks">1 mark</span> ### (c) State **two** possible causes of an exception. <span class="part-marks">2 marks</span>
Show mark scheme

8(a) [5 marks]

One mark for each correctly completed line ( Max 5 ) DECLARE Customer : TAccount DECLARE Location : INTEGER DECLARE AccountFile : STRING  AccountFile "AccountRecords.dat" OPENFILE AccountFile FOR RANDOM OUTPUT "Please enter an account number" INPUT Customer.AccountNumber  Location Hash( Customer.AccountNumber ) SEEK AccountFile , Location GETRECORD AccountFile, Customer OUTPUT Customer CLOSEFILE AccountFile

8(b) [1 mark]

One mark for correct definition (Exception handling is the process of) responding to an unexpected event when the program is running so it does not halt unexpectedly

8(c) [2 marks]

One mark per mark point ( Max 2 ), for example: • Programming errors • User errors • Hardware failure • Runtime errors

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)

Q12
Oct/Nov 2023 Paper 3 v2

(b) A pseudocode algorithm searches for a customer record in a random file AccountRecord.dat . A user inputs the name of the customer. 7 marks

The records are stored using the user‑defined data type TAccount .

TYPE TAccount
DECLARE AccountNumber : INTEGER
DECLARE Name : STRING
DECLARE Address : STRING
DECLARE Telephone : STRING
ENDTYPE

If the record is found, it is output, otherwise an error message is displayed.

Complete the file handling pseudocode.

DECLARE Customer : TAccount
DECLARE Location : INTEGER
DECLARE MaxSize : INTEGER
DECLARE FoundFlag : BOOLEAN
DECLARE SearchCustomer : STRING
MaxSize  1000

OPENFILE

Location  1

______ FALSE

OUTPUT "Enter the customer’s name"

______ AND Location <= MaxSize

______ "AccountRecord.dat",

GETRECORD "AccountRecord.dat", Customer
IF SearchCustomer = Customer.Name THEN
OUTPUT "Customer found: "
OUTPUT Customer      // output customer record
FoundFlag  TRUE
ENDIF
Location  Location + 1
ENDWHILE
IF NOT FoundFlag THEN

OUTPUT " ______ "

ENDIF
### (b) A pseudocode algorithm searches for a customer record in a random file `AccountRecord.dat` . A user inputs the name of the customer. <span class="part-marks">7 marks</span> The records are stored using the user‑defined data type `TAccount` . ``` TYPE TAccount ``` ``` DECLARE AccountNumber : INTEGER ``` ``` DECLARE Name : STRING ``` ``` DECLARE Address : STRING ``` ``` DECLARE Telephone : STRING ``` ``` ENDTYPE ``` If the record is found, it is output, otherwise an error message is displayed. Complete the file handling pseudocode. ``` DECLARE Customer : TAccount ``` ``` DECLARE Location : INTEGER ``` ``` DECLARE MaxSize : INTEGER ``` ``` DECLARE FoundFlag : BOOLEAN ``` ``` DECLARE SearchCustomer : STRING ``` ``` MaxSize 1000 ``` `OPENFILE` ``` Location 1 ``` ______ `FALSE` ``` OUTPUT "Enter the customer’s name" ``` ______ `AND Location <= MaxSize` ______ `"AccountRecord.dat",` ``` GETRECORD "AccountRecord.dat", Customer ``` ``` IF SearchCustomer = Customer.Name THEN ``` ``` OUTPUT "Customer found: " ``` ``` OUTPUT Customer // output customer record ``` ``` FoundFlag TRUE ``` ``` ENDIF ``` ``` Location Location + 1 ``` ``` ENDWHILE ``` ``` IF NOT FoundFlag THEN ``` `OUTPUT "` ______ `"` ``` ENDIF ```
Show mark scheme

12(a) [2 marks]

One mark for description, for example: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions / causes the program to halt execution One mark for example: • Hardware failure // hard disk crash • Programming error // trying to access out-of-bounds array element // divide by zero error // runtime error • User error // typing incorrect filename / data type

12(b) [7 marks]

One mark for each correctly completed blank ( Max 7 ) DECLARE Customer : TAccount DECLARE Location : INTEGER DECLARE MaxSize : INTEGER DECLARE: FoundFlag : BOOLEAN DECLARE SearchCustomer : STRING  MaxSize 1000 OPENFILE "AccountRecord.dat" FOR RANDOM  Location 1  FoundFlag FALSE OUTPUT "Enter the customer’s name" INPUT SearchCustomer WHILE NOT FoundFlag AND Location <= MaxSize SEEK "AccountRecord.dat", Location GETRECORD "AccountRecord.dat", Customer IF SearchCustomer = Customer.Name THEN OUTPUT "Customer found: " OUTPUT Customer  FoundFlag TRUE ENDIF  Location Location + 1 ENDWHILE IF NOT FoundFlag THEN OUTPUT " Customer does not exist. " ENDIF

Q8
Oct/Nov 2023 Paper 3 v3

(a) A pseudocode algorithm finds a customer account record in a random file and outputs it. The records are stored using the user-defined data type TAccount . 5 marks

    TYPE TAccount
    DECLARE AccountNumber : INTEGER
    DECLARE LastName : STRING
    DECLARE FirstName : STRING
    DECLARE Address : STRING
    DECLARE ContactNumber : STRING
    ENDTYPE

Complete the file handling pseudocode.

The function Hash() takes the customer account number as a parameter, calculates and returns the hash value.

    DECLARE Customer : TAccount
    DECLARE Location : INTEGER
    DECLARE AccountFile : STRING

______ "AccountRecords.dat"

______ AccountFile

    OUTPUT "Please enter an account number"
    INPUT Customer.AccountNumber

Location Hash( ______)

SEEK ______, Location

______ AccountFile,

    OUTPUT Customer       // output customer record
    CLOSEFILE AccountFile

(b) Define the term exception handling . 1 mark

(c) State two possible causes of an exception. 2 marks

### (a) A pseudocode algorithm finds a customer account record in a random file and outputs it. The records are stored using the user-defined data type `TAccount` . <span class="part-marks">5 marks</span> ``` TYPE TAccount DECLARE AccountNumber : INTEGER DECLARE LastName : STRING DECLARE FirstName : STRING DECLARE Address : STRING DECLARE ContactNumber : STRING ENDTYPE ``` Complete the file handling pseudocode. The function `Hash()` takes the customer account number as a parameter, calculates and returns the hash value. ``` DECLARE Customer : TAccount DECLARE Location : INTEGER DECLARE AccountFile : STRING ``` ______ `"AccountRecords.dat"` ______ `AccountFile` ``` OUTPUT "Please enter an account number" INPUT Customer.AccountNumber ``` `Location` `Hash(` ______) `SEEK` ______, `Location` ______ `AccountFile,` ``` OUTPUT Customer // output customer record CLOSEFILE AccountFile ``` ### (b) Define the term **exception handling** . <span class="part-marks">1 mark</span> ### (c) State **two** possible causes of an exception. <span class="part-marks">2 marks</span>
Show mark scheme

8(a) [5 marks]

One mark for each correctly completed line ( Max 5 ) DECLARE Customer : TAccount DECLARE Location : INTEGER DECLARE AccountFile : STRING  AccountFile "AccountRecords.dat" OPENFILE AccountFile FOR RANDOM OUTPUT "Please enter an account number" INPUT Customer.AccountNumber  Location Hash( Customer.AccountNumber ) SEEK AccountFile , Location GETRECORD AccountFile, Customer OUTPUT Customer CLOSEFILE AccountFile

8(b) [1 mark]

One mark for correct definition (Exception handling is the process of) responding to an unexpected event when the program is running so it does not halt unexpectedly

8(c) [2 marks]

One mark per mark point ( Max 2 ), for example: • Programming errors • User errors • Hardware failure • Runtime errors

Q2
Oct/Nov 2023 Paper 4 v1

A linear queue is implemented using the 1D array, Queue . The index of the first element in the array is 0.

(a) (i) Write program code to declare: 2 marks

  • Queue - a global array with space to store 50 IDs of type string

  • HeadPointer - a global variable to point to the first element in the queue, initialised to −1

  • TailPointer - a global variable to point to the next available space in the queue, initialised to 0.

Save your program as Question2_N23 .

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

(ii) The procedure Enqueue() takes a string parameter. 4 marks

If the queue is full, the procedure outputs a suitable message. If the queue is not full, the procedure inserts the parameter into the queue and updates the relevant pointer(s).

Write program code for Enqueue() .

Save your program.

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

(iii) The function Dequeue() checks if the queue is empty. 4 marks

If the queue is empty, the function outputs a suitable message and returns the string "Empty" . If the queue is not empty, the function returns the first element in the queue and updates the relevant pointer(s).

Write program code for Dequeue() .

Save your program.

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

(b) A shop sells computer games. Each game has a unique identifier (ID) of string data type. 6 marks

The text file QueueData.txt contains a list of game IDs.

The procedure ReadData() reads the data from the text file and inserts each item of data into the array Queue .

Write program code for the procedure ReadData() .

Save your program.

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

(c) Some game IDs appear in the text file more than once.

The program needs to total the number of times each game ID appears in the text file.

The record structure RecordData has the following fields:

  • ID - a string to store the game ID

  • Total - an integer to store the total number of times that game ID appears in the text file.

(i) Write program code to declare the record structure RecordData . 2 marks

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

Save your program.

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

(ii) The global 1D array Records stores up to 50 items of type RecordData . 2 marks

The global variable NumberRecords stores the number of records currently in the array Records and is initialised to 0.

Write program code to declare Records and NumberRecords .

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

Save your program.

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

(iii) The pseudocode algorithm for the procedure TotalData() : 5 marks

  • uses Dequeue() to remove an ID from the queue

  • checks whether a RecordData with the returned ID exists in Records

  • increments the total for that ID in the record if the ID already exists

  • creates a new record and stores it in Records if the ID does not exist.

   PROCEDURE TotalData()
   DECLARE DataAccessed : STRING
DECLARE Flag : BOOLEAN
DataAccessed  Dequeue()
# ←
Flag  FALSE
# ←
IF NumberRecords = 0 THEN
Records[NumberRecords].ID  DataAccessed
# ←
Records[NumberRecords].Total  1
# ←
Flag  TRUE
# ←
NumberRecords  NumberRecords + 1
# ←
ELSE
FOR X  0 TO NumberRecords - 1
# ←
IF Records[X].ID = DataAccessed THEN
Records[X].Total  Records[X].Total + 1
# ←
Flag  TRUE
# ←
ENDIF
NEXT X
ENDIF
IF Flag = FALSE THEN
Records[NumberRecords].ID  DataAccessed
# ←
Records[NumberRecords].Total  1
# ←
NumberRecords  NumberRecords + 1
# ←
ENDIF
      ENDPROCEDURE

Write program code for the procedure TotalData() .

Save your program.

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

(d) The procedure OutputRecords() outputs the ID and total of each record in Records in the format: 1 mark

      ID 1234  Total  4

Write program code for OutputRecords() .

Save your program.

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

(e) The main program needs to:

  • call ReadData()

  • call TotalData() for each element in the queue

  • call OutputRecords() .

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

Save your program.

Copy and paste the program code into part 2(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 2(e)(ii) in the evidence document.

A linear queue is implemented using the 1D array, `Queue` . The index of the first element in the array is 0. **(a) (i)** Write program code to declare: <span class="part-marks">2 marks</span> - `Queue` - a global array with space to store 50 IDs of type string - `HeadPointer` - a global variable to point to the first element in the queue, initialised to −1 - `TailPointer` - a global variable to point to the next available space in the queue, initialised to 0. Save your program as **Question2_N23** . Copy and paste the program code into part **2(a)(i)** in the evidence document. #### (ii) The procedure `Enqueue()` takes a string parameter. <span class="part-marks">4 marks</span> If the queue is full, the procedure outputs a suitable message. If the queue is not full, the procedure inserts the parameter into the queue and updates the relevant pointer(s). Write program code for `Enqueue()` . Save your program. Copy and paste the program code into part **2(a)(ii)** in the evidence document. #### (iii) The function `Dequeue()` checks if the queue is empty. <span class="part-marks">4 marks</span> If the queue is empty, the function outputs a suitable message and returns the string `"Empty"` . If the queue is not empty, the function returns the first element in the queue and updates the relevant pointer(s). Write program code for `Dequeue()` . Save your program. Copy and paste the program code into part **2(a)(iii)** in the evidence document. ### (b) A shop sells computer games. Each game has a unique identifier (ID) of string data type. <span class="part-marks">6 marks</span> The text file `QueueData.txt` contains a list of game IDs. The procedure `ReadData()` reads the data from the text file and inserts each item of data into the array `Queue` . Write program code for the procedure `ReadData()` . Save your program. Copy and paste the program code into part **2(b)** in the evidence document. ### (c) Some game IDs appear in the text file more than once. The program needs to total the number of times each game ID appears in the text file. The record structure `RecordData` has the following fields: - `ID` - a string to store the game ID - `Total` - an integer to store the total number of times that game ID appears in the text file. #### (i) Write program code to declare the record structure `RecordData` . <span class="part-marks">2 marks</span> If you are writing in Python, include attribute declarations as comments. Save your program. Copy and paste the program code into part **2(c)(i)** in the evidence document. #### (ii) The global 1D array `Records` stores up to 50 items of type `RecordData` . <span class="part-marks">2 marks</span> The global variable `NumberRecords` stores the number of records currently in the array `Records` and is initialised to 0. Write program code to declare `Records` and `NumberRecords` . If you are writing in Python, include attribute declarations as comments. Save your program. Copy and paste the program code into part **2(c)(ii)** in the evidence document. #### (iii) The pseudocode algorithm for the procedure `TotalData()` : <span class="part-marks">5 marks</span> - uses `Dequeue()` to remove an ID from the queue - checks whether a `RecordData` with the returned ID exists in `Records` - increments the total for that ID in the record if the ID already exists - creates a new record and stores it in `Records` if the ID does not exist. ``` PROCEDURE TotalData() DECLARE DataAccessed : STRING ``` ``` DECLARE Flag : BOOLEAN ``` ``` DataAccessed Dequeue() # ← ``` ``` Flag FALSE # ← ``` ``` IF NumberRecords = 0 THEN ``` ``` Records[NumberRecords].ID DataAccessed # ← ``` ``` Records[NumberRecords].Total 1 # ← ``` ``` Flag TRUE # ← ``` ``` NumberRecords NumberRecords + 1 # ← ``` ``` ELSE ``` ``` FOR X 0 TO NumberRecords - 1 # ← ``` ``` IF Records[X].ID = DataAccessed THEN ``` ``` Records[X].Total Records[X].Total + 1 # ← ``` ``` Flag TRUE # ← ``` ``` ENDIF ``` ``` NEXT X ENDIF ``` ``` IF Flag = FALSE THEN ``` ``` Records[NumberRecords].ID DataAccessed # ← ``` ``` Records[NumberRecords].Total 1 # ← ``` ``` NumberRecords NumberRecords + 1 # ← ``` ``` ENDIF ``` ``` ENDPROCEDURE ``` Write program code for the procedure `TotalData()` . Save your program. Copy and paste the program code into part **2(c)(iii)** in the evidence document. ### (d) The procedure `OutputRecords()` outputs the ID and total of each record in `Records` in the format: <span class="part-marks">1 mark</span> ``` ID 1234 Total 4 ``` Write program code for `OutputRecords()` . Save your program. Copy and paste the program code into part **2(d)** in the evidence document. ### (e) The main program needs to: - call `ReadData()` - call `TotalData()` for each element in the queue - call `OutputRecords()` . #### (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(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 **2(e)(ii)** in the evidence document.
Show mark scheme

2(a)(i) [2 marks]

One mark each • (Global) array with identifier with (minimum) 50 elements (of type string) Queue • (integer) initialised to 0, (integer) initialised to -1 TailPointer HeadPointer Example program code: Java public static String[] Queue = new String[50]; public static Integer HeadPointer = -1; public static Integer TailPointer = 0; VB.NET Dim Queue(50) As String Dim HeadPointer As Integer Dim TailPointer As Integer Sub Main(args As String()) HeadPointer = -1 TailPointer = 0 End Sub Python global Queue #string 50 elements global HeadPointer global TailPointer #main Queue = [] HeadPointer = -1 TailPointer = 0

2(a)(ii)

Python def Enqueue(Data): global TailPointer global HeadPointer global Queue if TailPointer == 50: print("Queue full") else: Queue.append(Data) TailPointer +=1 if HeadPointer == -1: HeadPointer = 0

2(a)(iii)

Python def Dequeue(): global Queue global HeadPointer if HeadPointer == -1 or HeadPointer == TailPointer: print("Queue empty") return "Empty" else: HeadPointer +=1 return Queue[HeadPointer - 1]

2(b)

DataReader.Close() Catch ex As Exception Console.WriteLine("No file") End Try End Sub Python def ReadData(): try: DataFile = open("QueueData.txt") for Line in DataFile: Enqueue(Line.strip()) DataFile.close() except IOError: print("No file")

2(c)(i)

self. ID = Value def GetID(self): return self. ID def SetTotal(self, Value): self. Total = Value def GetTotal(self): return self. Total

2(c)(ii) [2 marks]

One mark each • (global) 1D Array named of type Records RecordData • (global) declared as integer and initialised to 0 NumberRecords Example program code: Java public static RecordData[] Records = new RecordData[50]; public static Integer NumberRecords = 0; VB.NET Dim Records(49) As RecordData Dim NumberRecords As Integer Sub Main(args As String()) NumberRecords = 0 End Sub Python #main Records = [] #50 elements of type RecordData NumberRecords = 0

2(c)(iii)

Flag = True else: for X in range(0, NumberRecords): if(Records[X].GetID() == DataAccessed): Records[X].SetTotal(Records[X].GetTotal() + 1) Flag = True if Flag == False: Records.append(RecordData(DataAccessed, 1)) NumberRecords += 1

2(d) [1 mark]

One mark each • Looping through all array elements and outputting ID and total in correct format

System.out.println("ID ", Records[X].ID + " Total " + Records[X].Total); Console.WriteLine("ID " & Records(X).ID & " Total " & Records(X).Total) print("ID", Records[X].GetID(), " Total ", Records[X].GetTotal())

2(e)(i)

Python #main Queue = [] Records = [] HeadPointer = 0 TailPointer = 0 ReadData() NumberRecords = 0 while HeadPointer != TailPointer: TotalData() OutputRecords()

2(e)(ii) [1 mark]

One mark for screenshot e.g.

Q2
Oct/Nov 2023 Paper 4 v3

A linear queue is implemented using the 1D array, Queue . The index of the first element in the array is 0.

(a) (i) Write program code to declare: 2 marks

  • Queue - a global array with space to store 50 IDs of type string

  • HeadPointer - a global variable to point to the first element in the queue, initialised to −1

  • TailPointer - a global variable to point to the next available space in the queue, initialised to 0.

Save your program as Question2_N23 .

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

(ii) The procedure Enqueue() takes a string parameter. 4 marks

If the queue is full, the procedure outputs a suitable message. If the queue is not full, the procedure inserts the parameter into the queue and updates the relevant pointer(s).

Write program code for Enqueue() .

Save your program.

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

(iii) The function Dequeue() checks if the queue is empty. 4 marks

If the queue is empty, the function outputs a suitable message and returns the string "Empty" . If the queue is not empty, the function returns the first element in the queue and updates the relevant pointer(s).

Write program code for Dequeue() .

Save your program.

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

(b) A shop sells computer games. Each game has a unique identifier (ID) of string data type. 6 marks

The text file QueueData.txt contains a list of game IDs.

The procedure ReadData() reads the data from the text file and inserts each item of data into the array Queue .

Write program code for the procedure ReadData() .

Save your program.

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

(c) Some game IDs appear in the text file more than once.

The program needs to total the number of times each game ID appears in the text file.

The record structure RecordData has the following fields:

  • ID - a string to store the game ID

  • Total - an integer to store the total number of times that game ID appears in the text file.

(i) Write program code to declare the record structure RecordData . 2 marks

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

Save your program.

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

(ii) The global 1D array Records stores up to 50 items of type RecordData . 2 marks

The global variable NumberRecords stores the number of records currently in the array Records and is initialised to 0.

Write program code to declare Records and NumberRecords .

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

Save your program.

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

(iii) The pseudocode algorithm for the procedure TotalData() : 5 marks

  • uses Dequeue() to remove an ID from the queue

  • checks whether a RecordData with the returned ID exists in Records

  • increments the total for that ID in the record if the ID already exists

  • creates a new record and stores it in Records if the ID does not exist.

   PROCEDURE TotalData()
   DECLARE DataAccessed : STRING
DECLARE Flag : BOOLEAN
DataAccessed  Dequeue()
# ←
Flag  FALSE
# ←
IF NumberRecords = 0 THEN
Records[NumberRecords].ID  DataAccessed
# ←
Records[NumberRecords].Total  1
# ←
Flag  TRUE
# ←
NumberRecords  NumberRecords + 1
# ←
ELSE
FOR X  0 TO NumberRecords - 1
# ←
IF Records[X].ID = DataAccessed THEN
Records[X].Total  Records[X].Total + 1
# ←
Flag  TRUE
# ←
ENDIF
NEXT X
ENDIF
IF Flag = FALSE THEN
Records[NumberRecords].ID  DataAccessed
# ←
Records[NumberRecords].Total  1
# ←
NumberRecords  NumberRecords + 1
# ←
ENDIF
      ENDPROCEDURE

Write program code for the procedure TotalData() .

Save your program.

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

(d) The procedure OutputRecords() outputs the ID and total of each record in Records in the format: 1 mark

      ID 1234  Total  4

Write program code for OutputRecords() .

Save your program.

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

(e) The main program needs to:

  • call ReadData()

  • call TotalData() for each element in the queue

  • call OutputRecords() .

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

Save your program.

Copy and paste the program code into part 2(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 2(e)(ii) in the evidence document.

A linear queue is implemented using the 1D array, `Queue` . The index of the first element in the array is 0. **(a) (i)** Write program code to declare: <span class="part-marks">2 marks</span> - `Queue` - a global array with space to store 50 IDs of type string - `HeadPointer` - a global variable to point to the first element in the queue, initialised to −1 - `TailPointer` - a global variable to point to the next available space in the queue, initialised to 0. Save your program as **Question2_N23** . Copy and paste the program code into part **2(a)(i)** in the evidence document. #### (ii) The procedure `Enqueue()` takes a string parameter. <span class="part-marks">4 marks</span> If the queue is full, the procedure outputs a suitable message. If the queue is not full, the procedure inserts the parameter into the queue and updates the relevant pointer(s). Write program code for `Enqueue()` . Save your program. Copy and paste the program code into part **2(a)(ii)** in the evidence document. #### (iii) The function `Dequeue()` checks if the queue is empty. <span class="part-marks">4 marks</span> If the queue is empty, the function outputs a suitable message and returns the string `"Empty"` . If the queue is not empty, the function returns the first element in the queue and updates the relevant pointer(s). Write program code for `Dequeue()` . Save your program. Copy and paste the program code into part **2(a)(iii)** in the evidence document. ### (b) A shop sells computer games. Each game has a unique identifier (ID) of string data type. <span class="part-marks">6 marks</span> The text file `QueueData.txt` contains a list of game IDs. The procedure `ReadData()` reads the data from the text file and inserts each item of data into the array `Queue` . Write program code for the procedure `ReadData()` . Save your program. Copy and paste the program code into part **2(b)** in the evidence document. ### (c) Some game IDs appear in the text file more than once. The program needs to total the number of times each game ID appears in the text file. The record structure `RecordData` has the following fields: - `ID` - a string to store the game ID - `Total` - an integer to store the total number of times that game ID appears in the text file. #### (i) Write program code to declare the record structure `RecordData` . <span class="part-marks">2 marks</span> If you are writing in Python, include attribute declarations as comments. Save your program. Copy and paste the program code into part **2(c)(i)** in the evidence document. #### (ii) The global 1D array `Records` stores up to 50 items of type `RecordData` . <span class="part-marks">2 marks</span> The global variable `NumberRecords` stores the number of records currently in the array `Records` and is initialised to 0. Write program code to declare `Records` and `NumberRecords` . If you are writing in Python, include attribute declarations as comments. Save your program. Copy and paste the program code into part **2(c)(ii)** in the evidence document. #### (iii) The pseudocode algorithm for the procedure `TotalData()` : <span class="part-marks">5 marks</span> - uses `Dequeue()` to remove an ID from the queue - checks whether a `RecordData` with the returned ID exists in `Records` - increments the total for that ID in the record if the ID already exists - creates a new record and stores it in `Records` if the ID does not exist. ``` PROCEDURE TotalData() DECLARE DataAccessed : STRING ``` ``` DECLARE Flag : BOOLEAN ``` ``` DataAccessed Dequeue() # ← ``` ``` Flag FALSE # ← ``` ``` IF NumberRecords = 0 THEN ``` ``` Records[NumberRecords].ID DataAccessed # ← ``` ``` Records[NumberRecords].Total 1 # ← ``` ``` Flag TRUE # ← ``` ``` NumberRecords NumberRecords + 1 # ← ``` ``` ELSE ``` ``` FOR X 0 TO NumberRecords - 1 # ← ``` ``` IF Records[X].ID = DataAccessed THEN ``` ``` Records[X].Total Records[X].Total + 1 # ← ``` ``` Flag TRUE # ← ``` ``` ENDIF ``` ``` NEXT X ENDIF ``` ``` IF Flag = FALSE THEN ``` ``` Records[NumberRecords].ID DataAccessed # ← ``` ``` Records[NumberRecords].Total 1 # ← ``` ``` NumberRecords NumberRecords + 1 # ← ``` ``` ENDIF ``` ``` ENDPROCEDURE ``` Write program code for the procedure `TotalData()` . Save your program. Copy and paste the program code into part **2(c)(iii)** in the evidence document. ### (d) The procedure `OutputRecords()` outputs the ID and total of each record in `Records` in the format: <span class="part-marks">1 mark</span> ``` ID 1234 Total 4 ``` Write program code for `OutputRecords()` . Save your program. Copy and paste the program code into part **2(d)** in the evidence document. ### (e) The main program needs to: - call `ReadData()` - call `TotalData()` for each element in the queue - call `OutputRecords()` . #### (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(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 **2(e)(ii)** in the evidence document.
Show mark scheme

2(a)(i) [2 marks]

One mark each • (Global) array with identifier with (minimum) 50 elements (of type string) Queue • (integer) initialised to 0, (integer) initialised to -1 TailPointer HeadPointer Example program code: Java public static String[] Queue = new String[50]; public static Integer HeadPointer = -1; public static Integer TailPointer = 0; VB.NET Dim Queue(50) As String Dim HeadPointer As Integer Dim TailPointer As Integer Sub Main(args As String()) HeadPointer = -1 TailPointer = 0 End Sub Python global Queue #string 50 elements global HeadPointer global TailPointer #main Queue = [] HeadPointer = -1 TailPointer = 0

2(a)(ii)

Python def Enqueue(Data): global TailPointer global HeadPointer global Queue if TailPointer == 50: print("Queue full") else: Queue.append(Data) TailPointer +=1 if HeadPointer == -1: HeadPointer = 0

2(a)(iii)

Python def Dequeue(): global Queue global HeadPointer if HeadPointer == -1 or HeadPointer == TailPointer: print("Queue empty") return "Empty" else: HeadPointer +=1 return Queue[HeadPointer - 1]

2(b)

DataReader.Close() Catch ex As Exception Console.WriteLine("No file") End Try End Sub Python def ReadData(): try: DataFile = open("QueueData.txt") for Line in DataFile: Enqueue(Line.strip()) DataFile.close() except IOError: print("No file")

2(c)(i)

self. ID = Value def GetID(self): return self. ID def SetTotal(self, Value): self. Total = Value def GetTotal(self): return self. Total

2(c)(ii) [2 marks]

One mark each • (global) 1D Array named of type Records RecordData • (global) declared as integer and initialised to 0 NumberRecords Example program code: Java public static RecordData[] Records = new RecordData[50]; public static Integer NumberRecords = 0; VB.NET Dim Records(49) As RecordData Dim NumberRecords As Integer Sub Main(args As String()) NumberRecords = 0 End Sub Python #main Records = [] #50 elements of type RecordData NumberRecords = 0

2(c)(iii)

Flag = True else: for X in range(0, NumberRecords): if(Records[X].GetID() == DataAccessed): Records[X].SetTotal(Records[X].GetTotal() + 1) Flag = True if Flag == False: Records.append(RecordData(DataAccessed, 1)) NumberRecords += 1

2(d) [1 mark]

One mark each • Looping through all array elements and outputting ID and total in correct format

System.out.println("ID ", Records[X].ID + " Total " + Records[X].Total); Console.WriteLine("ID " & Records(X).ID & " Total " & Records(X).Total) print("ID", Records[X].GetID(), " Total ", Records[X].GetTotal())

2(e)(i)

Python #main Queue = [] Records = [] HeadPointer = 0 TailPointer = 0 ReadData() NumberRecords = 0 while HeadPointer != TailPointer: TotalData() OutputRecords()

2(e)(ii) [1 mark]

One mark for screenshot e.g.

Q10
May/Jun 2023 Paper 3 v1

The pseudocode algorithm shown copies an active accounts text file ActiveFile.txt to an archive accounts text file ArchiveFile.txt, one line at a time. Any blank lines found in the active accounts text file are replaced with the words "Account not present" in the archive accounts text file.

Complete this file-handling pseudocode.

  DECLARE Account : STRING
  OPENFILE "ArchiveFile.txt" FOR WRITE

WHILE NOT

  READFILE "ActiveFile.txt", Account
  IF Account = "" THEN

WRITEFILE "ArchiveFile.txt", " ______ "

  ELSE

WRITEFILE "ArchiveFile.txt",

  ENDIF
  ENDWHILE
  CLOSEFILE "ArchiveFile.txt"

5 marks

The pseudocode algorithm shown copies an active accounts text file `ActiveFile.txt` to an archive accounts text file `ArchiveFile.txt`, one line at a time. Any blank lines found in the active accounts text file are replaced with the words `"Account not present"` in the archive accounts text file. Complete this file-handling pseudocode. ``` DECLARE Account : STRING ``` ``` OPENFILE "ArchiveFile.txt" FOR WRITE ``` `WHILE NOT` ``` READFILE "ActiveFile.txt", Account IF Account = "" THEN ``` `WRITEFILE "ArchiveFile.txt", "` ______ `"` ``` ELSE ``` `WRITEFILE "ArchiveFile.txt",` ``` ENDIF ENDWHILE ``` ``` CLOSEFILE "ArchiveFile.txt" ``` <span class="part-marks">5 marks</span>
Show mark scheme

10 [3 marks]

One mark for each correctly completed line ( Max 5 ) DECLARE Account : STRING OPENFILE "ActiveFile.txt" FOR READ OPENFILE "ArchiveFile.txt" FOR WRITE WHILE NOT EOF("ActiveFile.txt") READFILE "ActiveFile.txt", Account IF Account = "" THEN WRITEFILE "ArchiveFile.txt", " Account not present " ELSE WRITEFILE "ArchiveFile.txt", Account ENDIF ENDWHILE CLOSEFILE "ActiveFile.txt" CLOSEFILE "ArchiveFile.txt"

Q10
May/Jun 2023 Paper 3 v3

The pseudocode algorithm shown copies an active accounts text file ActiveFile.txt to an archive accounts text file ArchiveFile.txt, one line at a time. Any blank lines found in the active accounts text file are replaced with the words "Account not present" in the archive accounts text file.

Complete this file-handling pseudocode.

  DECLARE Account : STRING
  OPENFILE "ArchiveFile.txt" FOR WRITE

WHILE NOT

  READFILE "ActiveFile.txt", Account
  IF Account = "" THEN

WRITEFILE "ArchiveFile.txt", " ______ "

  ELSE

WRITEFILE "ArchiveFile.txt",

  ENDIF
  ENDWHILE
  CLOSEFILE "ArchiveFile.txt"

5 marks

The pseudocode algorithm shown copies an active accounts text file `ActiveFile.txt` to an archive accounts text file `ArchiveFile.txt`, one line at a time. Any blank lines found in the active accounts text file are replaced with the words `"Account not present"` in the archive accounts text file. Complete this file-handling pseudocode. ``` DECLARE Account : STRING ``` ``` OPENFILE "ArchiveFile.txt" FOR WRITE ``` `WHILE NOT` ``` READFILE "ActiveFile.txt", Account IF Account = "" THEN ``` `WRITEFILE "ArchiveFile.txt", "` ______ `"` ``` ELSE ``` `WRITEFILE "ArchiveFile.txt",` ``` ENDIF ENDWHILE ``` ``` CLOSEFILE "ArchiveFile.txt" ``` <span class="part-marks">5 marks</span>
Show mark scheme

10 [3 marks]

One mark for each correctly completed line ( Max 5 ) DECLARE Account : STRING OPENFILE "ActiveFile.txt" FOR READ OPENFILE "ArchiveFile.txt" FOR WRITE WHILE NOT EOF("ActiveFile.txt") READFILE "ActiveFile.txt", Account IF Account = "" THEN WRITEFILE "ArchiveFile.txt", " Account not present " ELSE WRITEFILE "ArchiveFile.txt", Account ENDIF ENDWHILE CLOSEFILE "ActiveFile.txt" CLOSEFILE "ArchiveFile.txt"

Q1
May/Jun 2023 Paper 4 v1

A program reads data from a file and searches for specific data.

(a) The main program needs to read 25 integer data items from the text file Data.txt into a local 1D array, DataArray

(i) Write program code to declare the local array DataArray Save your program as Question1_J2023 . 1 mark

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

(ii) Amend the main program to read the contents of Data.txt into DataArray Save your program. 4 marks

Copy and paste the program code into part 1(a)(ii) in the evidence document. (b) (i) The procedure PrintArray() takes an integer array as a parameter and outputs the 3 marks contents of the array in the order they are stored.

The items are printed on the same line, for example:

10 4 5 13 25

Write program code for the procedure PrintArray()

Save your program.

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

A program reads data from a file and searches for specific data. ### (a) The main program needs to read 25 integer data items from the text file `Data.txt` into a local 1D array, `DataArray` #### (i) Write program code to declare the local array `DataArray` Save your program as **Question1_J2023** . <span class="part-marks">1 mark</span> Copy and paste the program code into **part 1(a)(i)** in the evidence document. #### (ii) Amend the main program to read the contents of `Data.txt` into `DataArray` Save your program. <span class="part-marks">4 marks</span> Copy and paste the program code into **part 1(a)(ii)** in the evidence document. **(b) (i)** The procedure `PrintArray()` takes an integer array as a parameter and outputs the <span class="part-marks">3 marks</span> contents of the array in the order they are stored. The items are printed on the same line, for example: 10 4 5 13 25 Write program code for the procedure `PrintArray()` Save your program. Copy and paste the program code into **part 1(b)(i)** in the evidence document.
Show mark scheme

1(a)(i) [1 mark]

1 mark for 1D array with name DataArray (with 25 elements of type Integer) Example program code: public static Integer[] DataArray = new Integer[25]; VB.NET Dim DataArray(24) As Integer Python DataArray = [] #25 elements Integer

1(a)(ii)

Python DataFile = open("Data.txt",'r') for Line in DataFile: DataArray.append(int(Line)) DataFile.close() except IOError: print("Could not find file")

1(b)(i) [3 marks]

1 mark each Procedure header (and close where appropriate) with (at least) one (integer array) parameter Outputting all (25) array elements … …on one line Example program code: public static void PrintArray(Integer[] DataArray){ String OutputData; for(Integer X = 0; X < DataArray.length - 1; X++){ OutputData = OutputData + DataArray[X] + " "; } System.out.print(OutputData); VB.NET Sub PrintArray(DataArray) Dim OutputData As String = ""; For x = 0 To DataArray.length - 1 OutputData = OutputData & DataArray(x) & " " Next Console.WriteLine(OutputData) End Sub Python def PrintArray(DataArray): output = "" for X in range(0, len(DataArray)): output = output + str((DataArray[X])) + " " print(output)

1(b)(ii) [1 mark]

1 mark for calling PrintArray with the array as a parameter Example program code: PrintArray(DataArray); VB.NET PrintArray(DataArray) Python PrintArray(DataArray)

1(b)(iii) [1 mark]

1 mark for screenshot

1(c) [3 marks]

1 mark each Function header (and close where appropriate) taking array and search value as parameters Looping through each array element and keeping count of the number of times the parameter appears Returning the calculated count value Example program code: public static Integer LinearSearch(Integer[] DataArray, Integer DataToFind){ Integer Count = 0; for(Integer x = 0; x < DataArray.length - 1; x++){ if(DataArray[x] == DataToFind){ Count++; } } return Count; VB.NET Function LinearSearch(DataArray, DataToFind) Dim Count As Integer = 0 For x = 0 To DataArray.length - 1 If DataArray(x) = DataToFind Then Count = Count + 1 End If Next Return Count End Function Python def LinearSearch(DataArray, DataToFind): Count = 0 for X in range(0, len(DataArray)): if(DataArray[X] == DataToFind): Count +=1 return Count

1(d)(i) [4 marks]

1 mark each Prompt and reading input … …with validation for whole number between 0 and 100 inclusive Calling LinearSearch() with array and valid data input and storing/using return value Output of the message with return value Example program code: System.out.println("Enter a number to find"); Integer DataToFind = -1; Scanner NewScanner = new Scanner(System.in); while(DataToFind < 0 || DataToFind > 100){ DataToFind = Integer.parseInt(NewScanner.nextLine()); Integer NumberTimes = LinearSearch(DataArray, DataToFind); System.out.println("The number " + DataToFind + " is found " + NumberTimes + " times"); VB.NET Console.WriteLine("Enter a number to find ") Dim DataToFind As Integer = -1 Do Until DataToFind >= 0 And DataToFind <= 100 DataToFind = Console.ReadLine() Dim NumberTimes = LinearSearch(DataArray, DataToFind) Console.WriteLine("The number " & DataToFind & " is found " & NumberTimes & " times.") Python DataToFind = int(input("Enter a number to find ")) while DataToFind < 0 or DataToFind > 100: DataToFind = int(input("Enter a number to find ")) NumberTimes = LinearSearch(DataArray, DataToFind) print("The number", DataToFind, "is found", NumberTimes, "times")

1(d)(ii) [1 mark]

1 mark for screenshot e.g.

Q3
May/Jun 2023 Paper 4 v1

A program implements two stacks using 1D arrays. One stack stores the names of colours. One stack stores the names of animals.

(a) The program contains the following global arrays and variables: 3 marks

  • 1D array Animal to store the names of up to 20 animals.

  • 1D array Colour to store the names of up to 10 colours.

  • AnimalTopPointer to point to the next free space in the array Animal, initialised to 0.

  • ColourTopPointer to point to the next free space in the array Colour, initialised to 0.

Write program code to declare the global arrays and variables.

Save your program as Question3_J2023 .

Copy and paste the program code into part 3(a) in the evidence document. (b) (i) Study the pseudocode function PushAnimal() : 3 marks

     FUNCTION PushAnimal(DataToPush : STRING) RETURNS BOOLEAN
     IF AnimalTopPointer = 20 THEN
     RETURN FALSE
     ELSE
     Animal[AnimalTopPointer]  DataToPush
     AnimalTopPointer  AnimalTopPointer + 1
     RETURN TRUE
     ENDIF
     ENDFUNCTION

Write program code for the function PushAnimal()

Save your program.

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

(ii) Study the pseudocode function PopAnimal() : 3 marks

     FUNCTION PopAnimal() RETURNS STRING
     DECLARE ReturnData : STRING
     IF AnimalTopPointer = 0 THEN
     RETURN ""
     ELSE
     ReturnData  Animal[AnimalTopPointer - 1]
     AnimalTopPointer  AnimalTopPointer - 1
     RETURN ReturnData
     ENDIF
     ENDFUNCTION

Write program code to declare the function PopAnimal()

Save your program.

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

(iii) The procedure ReadData() : 5 marks

  • reads the animal names from the file AnimalData.txt

  • uses PushAnimal() to insert each name onto the stack

  • uses appropriate exception handling if the file does not exist.

Write program code for the procedure ReadData()

Save your program.

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

(iv) The function PushColour() performs the same actions as PushAnimal() but inserts an item into Colour . 2 marks

The function PopColour() performs the same actions as PopAnimal() but removes the next item from Colour .

Write program code for the functions PushColour() and PopColour()

Save your program.

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

(v) Amend the procedure ReadData() so that it also:

  • reads the colours from the text file ColourData.txt

  • uses PushColour() to insert each colour onto the stack

  • uses appropriate exception handling if the file does not exist.

Save your program.

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

(c) The procedure OutputItem() : 2 marks

  • pops the next item from both Animal and Colour

  • outputs the colour and animal on one line, for example "black horse"

If there is no data in Colour :

  • the animal is pushed back onto Animal

  • "No colour" is output.

If there is no data in Animal :

  • the colour is pushed back onto Colour

  • "No animal" is output.

Write program code for the procedure OutputItem()

Save your program.

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

(d) The main program: 5 marks

  • calls the procedure ReadData()

  • calls OutputItem() four times.

(i) Write program code for the main program. 1 mark

Save your program.

Copy and paste the program code into part 3(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 3(d)(ii) in the evidence document.

A program implements two stacks using 1D arrays. One stack stores the names of colours. One stack stores the names of animals. ### (a) The program contains the following global arrays and variables: <span class="part-marks">3 marks</span> - 1D array `Animal` to store the names of up to 20 animals. - 1D array `Colour` to store the names of up to 10 colours. - `AnimalTopPointer` to point to the next free space in the array `Animal`, initialised to 0. - `ColourTopPointer` to point to the next free space in the array `Colour`, initialised to 0. Write program code to declare the global arrays and variables. Save your program as **Question3_J2023** . Copy and paste the program code into **part 3(a)** in the evidence document. **(b) (i)** Study the pseudocode function `PushAnimal()` : <span class="part-marks">3 marks</span> ``` FUNCTION PushAnimal(DataToPush : STRING) RETURNS BOOLEAN IF AnimalTopPointer = 20 THEN RETURN FALSE ELSE Animal[AnimalTopPointer] DataToPush AnimalTopPointer AnimalTopPointer + 1 RETURN TRUE ENDIF ENDFUNCTION ``` Write program code for the function `PushAnimal()` Save your program. Copy and paste the program code into **part 3(b)(i)** in the evidence document. #### (ii) Study the pseudocode function `PopAnimal()` : <span class="part-marks">3 marks</span> ``` FUNCTION PopAnimal() RETURNS STRING DECLARE ReturnData : STRING IF AnimalTopPointer = 0 THEN RETURN "" ELSE ReturnData Animal[AnimalTopPointer - 1] AnimalTopPointer AnimalTopPointer - 1 RETURN ReturnData ENDIF ENDFUNCTION ``` Write program code to declare the function `PopAnimal()` Save your program. Copy and paste the program code into **part 3(b)(ii)** in the evidence document. #### (iii) The procedure `ReadData()` : <span class="part-marks">5 marks</span> - reads the animal names from the file `AnimalData.txt` - uses `PushAnimal()` to insert each name onto the stack - uses appropriate exception handling if the file does not exist. Write program code for the procedure `ReadData()` Save your program. Copy and paste the program code into **part 3(b)(iii)** in the evidence document. #### (iv) The function `PushColour()` performs the same actions as `PushAnimal()` but inserts an item into `Colour` . <span class="part-marks">2 marks</span> The function `PopColour()` performs the same actions as `PopAnimal()` but removes the next item from `Colour` . Write program code for the functions `PushColour()` and `PopColour()` Save your program. Copy and paste the program code into **part 3(b)(iv)** in the evidence document. #### (v) Amend the procedure `ReadData()` so that it also: - reads the colours from the text file `ColourData.txt` - uses `PushColour()` to insert each colour onto the stack - uses appropriate exception handling if the file does not exist. Save your program. Copy and paste the program code into **part 3(b)(v)** in the evidence document. ### (c) The procedure `OutputItem()` : <span class="part-marks">2 marks</span> - pops the next item from both `Animal` and `Colour` - outputs the colour and animal on one line, for example `"black horse"` If there is no data in `Colour` : - the animal is pushed back onto `Animal` - `"No colour"` is output. If there is no data in `Animal` : - the colour is pushed back onto `Colour` - `"No animal"` is output. Write program code for the procedure `OutputItem()` Save your program. Copy and paste the program code into **part 3(c)** in the evidence document. ### (d) The main program: <span class="part-marks">5 marks</span> - calls the procedure `ReadData()` - calls `OutputItem()` **four** times. #### (i) Write program code for the main program. <span class="part-marks">1 mark</span> Save your program. Copy and paste the program code into **part 3(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 3(d)(ii)** in the evidence document.
Show mark scheme

3(a) [3 marks]

1 mark each (Global) Animal array (with 20 string elements) (Global) Colour array (with 10 string elements) (Global) AnimalTopPointer and ColourTopPointer initialised to 0 Example program code: public static String[] Animal = new String[20]; public static String[] Colour = new String[10]; public static Integer AnimalTopPointer = 0; public static Integer ColourTopPointer = 0; VB.NET Dim Animal(0 to 19) As String Dim Colour(0 to 9) As String Dim AnimalTopPointer As Integer = 0 Dim ColourTopPointer As Integer = 0 Python Animal = [] #20 elements Colour = [] #10 elements global AnimalTopPointer global ColourTopPointer AnimalTopPointer = 0 ColourTopPointer = 0

3(b)(i)

else: Animal.append(DataToPush) AnimalTopPointer +=1 return True

3(b)(ii)

Python def PopAnimal(): global AnimalTopPointer global ColourTopPointer if AnimalTopPointer == 0: return "" else: ReturnData = Animal[AnimalTopPointer - 1] AnimalTopPointer -=1 return ReturnData

3(b)(iii)

Python def ReadData(): try: global AnimalTopPointer global ColourTopPointer AnimalFile = open("AnimalData.txt", 'r') for Line in AnimalFile: PushAnimal(Line) AnimalFile.close() except IOError: print("Could not find file")

3(b)(iv)

End Function Function PopColour() Dim ReturnData As String If ColourTopPointer = 0 Then Return "" Else ReturnData = Colour(ColourTopPointer - 1) ColourTopPointer = ColourTopPointer - 1 Return ReturnData End If End Function Python def PushColour(DataToPush): global AnimalTopPointer global ColourTopPointer if ColourTopPointer == 10: return False else: Colour.append(DataToPush) ColourTopPointer +=1 return True def PopColour(): global AnimalTopPointer global ColourTopPointer if ColourTopPointer == 0: return "" else: ReturnData = Colour[ColourTopPointer - 1] ColourTopPointer -=1 return ReturnData

3(b)(v)

Loop AnimalFileReader.Close() Dim ColourFile As String = "ColourData.txt" Dim ColourFileReader As New System.IO.StreamReader(ColourFile) Do Until ColourFileReader.EndOfStream PushColour(ColourFileReader.ReadLine()) Loop ColourFileReader.Close() Catch ex As Exception Console.WriteLine("Invalid file") End Try End Sub Python def ReadData(): try: global AnimalTopPointer global ColourTopPointer AnimalFile = open("AnimalData.txt", 'r') for Line in AnimalFile: PushAnimal(Line) AnimalFile.close() ColourFile = open("ColourData.txt", 'r') for Line in ColourFile: PushColour(Line) ColourFile.close() except IOError: print("Could not find file")

3(c)

Else If Animalreturned = "" Then Console.WriteLine("No animal") PushColour(ColourReturned) Else Console.WriteLine("A " & ColourReturned & " " & Animalreturned) End If End If End Sub Python def OutputItem(): global AnimalTopPointer global ColourTopPointer ColourReturned = PopColour() AnimalReturned = PopAnimal() if ColourReturned == "": print("No colour") PushAnimal(AnimalReturned) else: if AnimalReturned == "": print("No animal") PushColour(ColourReturned) else: print(ColourReturned, AnimalReturned)

3(d)(i) [1 mark]

1 mark for Calling ReadData() and calling OutputItem() 4 times Example program code: public static void main(String args[]){ ReadData(); OutputItem(); OutputItem(); OutputItem(); OutputItem(); VB.NET Sub Main() ReadData() OutputItem() OutputItem() OutputItem() OutputItem() End Sub Python ReadData() OutputItem() OutputItem() OutputItem() OutputItem()

3(d)(ii) [1 mark]

1 mark for output

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.

Q1
May/Jun 2023 Paper 4 v3

A program reads data from a file and searches for specific data.

(a) The main program needs to read 25 integer data items from the text file Data.txt into a local 1D array, DataArray

(i) Write program code to declare the local array DataArray Save your program as Question1_J2023 . 1 mark

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

(ii) Amend the main program to read the contents of Data.txt into DataArray Save your program. 4 marks

Copy and paste the program code into part 1(a)(ii) in the evidence document. (b) (i) The procedure PrintArray() takes an integer array as a parameter and outputs the 3 marks contents of the array in the order they are stored.

The items are printed on the same line, for example:

10 4 5 13 25

Write program code for the procedure PrintArray()

Save your program.

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

A program reads data from a file and searches for specific data. ### (a) The main program needs to read 25 integer data items from the text file `Data.txt` into a local 1D array, `DataArray` #### (i) Write program code to declare the local array `DataArray` Save your program as **Question1_J2023** . <span class="part-marks">1 mark</span> Copy and paste the program code into **part 1(a)(i)** in the evidence document. #### (ii) Amend the main program to read the contents of `Data.txt` into `DataArray` Save your program. <span class="part-marks">4 marks</span> Copy and paste the program code into **part 1(a)(ii)** in the evidence document. **(b) (i)** The procedure `PrintArray()` takes an integer array as a parameter and outputs the <span class="part-marks">3 marks</span> contents of the array in the order they are stored. The items are printed on the same line, for example: 10 4 5 13 25 Write program code for the procedure `PrintArray()` Save your program. Copy and paste the program code into **part 1(b)(i)** in the evidence document.
Show mark scheme

1(a)(i) [1 mark]

1 mark for 1D array with name DataArray (with 25 elements of type Integer) Example program code: public static Integer[] DataArray = new Integer[25]; VB.NET Dim DataArray(24) As Integer Python DataArray = [] #25 elements Integer

1(a)(ii)

Python DataFile = open("Data.txt",'r') for Line in DataFile: DataArray.append(int(Line)) DataFile.close() except IOError: print("Could not find file")

1(b)(i) [3 marks]

1 mark each Procedure header (and close where appropriate) with (at least) one (integer array) parameter Outputting all (25) array elements … …on one line Example program code: public static void PrintArray(Integer[] DataArray){ String OutputData; for(Integer X = 0; X < DataArray.length - 1; X++){ OutputData = OutputData + DataArray[X] + " "; } System.out.print(OutputData); VB.NET Sub PrintArray(DataArray) Dim OutputData As String = ""; For x = 0 To DataArray.length - 1 OutputData = OutputData & DataArray(x) & " " Next Console.WriteLine(OutputData) End Sub Python def PrintArray(DataArray): output = "" for X in range(0, len(DataArray)): output = output + str((DataArray[X])) + " " print(output)

1(b)(ii) [1 mark]

1 mark for calling PrintArray with the array as a parameter Example program code: PrintArray(DataArray); VB.NET PrintArray(DataArray) Python PrintArray(DataArray)

1(b)(iii) [1 mark]

1 mark for screenshot

1(c) [3 marks]

1 mark each Function header (and close where appropriate) taking array and search value as parameters Looping through each array element and keeping count of the number of times the parameter appears Returning the calculated count value Example program code: public static Integer LinearSearch(Integer[] DataArray, Integer DataToFind){ Integer Count = 0; for(Integer x = 0; x < DataArray.length - 1; x++){ if(DataArray[x] == DataToFind){ Count++; } } return Count; VB.NET Function LinearSearch(DataArray, DataToFind) Dim Count As Integer = 0 For x = 0 To DataArray.length - 1 If DataArray(x) = DataToFind Then Count = Count + 1 End If Next Return Count End Function Python def LinearSearch(DataArray, DataToFind): Count = 0 for X in range(0, len(DataArray)): if(DataArray[X] == DataToFind): Count +=1 return Count

1(d)(i) [4 marks]

1 mark each Prompt and reading input … …with validation for whole number between 0 and 100 inclusive Calling LinearSearch() with array and valid data input and storing/using return value Output of the message with return value Example program code: System.out.println("Enter a number to find"); Integer DataToFind = -1; Scanner NewScanner = new Scanner(System.in); while(DataToFind < 0 || DataToFind > 100){ DataToFind = Integer.parseInt(NewScanner.nextLine()); Integer NumberTimes = LinearSearch(DataArray, DataToFind); System.out.println("The number " + DataToFind + " is found " + NumberTimes + " times"); VB.NET Console.WriteLine("Enter a number to find ") Dim DataToFind As Integer = -1 Do Until DataToFind >= 0 And DataToFind <= 100 DataToFind = Console.ReadLine() Dim NumberTimes = LinearSearch(DataArray, DataToFind) Console.WriteLine("The number " & DataToFind & " is found " & NumberTimes & " times.") Python DataToFind = int(input("Enter a number to find ")) while DataToFind < 0 or DataToFind > 100: DataToFind = int(input("Enter a number to find ")) NumberTimes = LinearSearch(DataArray, DataToFind) print("The number", DataToFind, "is found", NumberTimes, "times")

1(d)(ii) [1 mark]

1 mark for screenshot e.g.

Q3
May/Jun 2023 Paper 4 v3

A program implements two stacks using 1D arrays. One stack stores the names of colours. One stack stores the names of animals.

(a) The program contains the following global arrays and variables: 3 marks

  • 1D array Animal to store the names of up to 20 animals.

  • 1D array Colour to store the names of up to 10 colours.

  • AnimalTopPointer to point to the next free space in the array Animal, initialised to 0.

  • ColourTopPointer to point to the next free space in the array Colour, initialised to 0.

Write program code to declare the global arrays and variables.

Save your program as Question3_J2023 .

Copy and paste the program code into part 3(a) in the evidence document. (b) (i) Study the pseudocode function PushAnimal() : 3 marks

     FUNCTION PushAnimal(DataToPush : STRING) RETURNS BOOLEAN
     IF AnimalTopPointer = 20 THEN
     RETURN FALSE
     ELSE
     Animal[AnimalTopPointer]  DataToPush
     AnimalTopPointer  AnimalTopPointer + 1
     RETURN TRUE
     ENDIF
     ENDFUNCTION

Write program code for the function PushAnimal()

Save your program.

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

(ii) Study the pseudocode function PopAnimal() : 3 marks

     FUNCTION PopAnimal() RETURNS STRING
     DECLARE ReturnData : STRING
     IF AnimalTopPointer = 0 THEN
     RETURN ""
     ELSE
     ReturnData  Animal[AnimalTopPointer - 1]
     AnimalTopPointer  AnimalTopPointer - 1
     RETURN ReturnData
     ENDIF
     ENDFUNCTION

Write program code to declare the function PopAnimal()

Save your program.

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

(iii) The procedure ReadData() : 5 marks

  • reads the animal names from the file AnimalData.txt

  • uses PushAnimal() to insert each name onto the stack

  • uses appropriate exception handling if the file does not exist.

Write program code for the procedure ReadData()

Save your program.

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

(iv) The function PushColour() performs the same actions as PushAnimal() but inserts an item into Colour . 2 marks

The function PopColour() performs the same actions as PopAnimal() but removes the next item from Colour .

Write program code for the functions PushColour() and PopColour()

Save your program.

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

(v) Amend the procedure ReadData() so that it also:

  • reads the colours from the text file ColourData.txt

  • uses PushColour() to insert each colour onto the stack

  • uses appropriate exception handling if the file does not exist.

Save your program.

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

(c) The procedure OutputItem() : 2 marks

  • pops the next item from both Animal and Colour

  • outputs the colour and animal on one line, for example "black horse"

If there is no data in Colour :

  • the animal is pushed back onto Animal

  • "No colour" is output.

If there is no data in Animal :

  • the colour is pushed back onto Colour

  • "No animal" is output.

Write program code for the procedure OutputItem()

Save your program.

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

(d) The main program: 5 marks

  • calls the procedure ReadData()

  • calls OutputItem() four times.

(i) Write program code for the main program. 1 mark

Save your program.

Copy and paste the program code into part 3(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 3(d)(ii) in the evidence document.

A program implements two stacks using 1D arrays. One stack stores the names of colours. One stack stores the names of animals. ### (a) The program contains the following global arrays and variables: <span class="part-marks">3 marks</span> - 1D array `Animal` to store the names of up to 20 animals. - 1D array `Colour` to store the names of up to 10 colours. - `AnimalTopPointer` to point to the next free space in the array `Animal`, initialised to 0. - `ColourTopPointer` to point to the next free space in the array `Colour`, initialised to 0. Write program code to declare the global arrays and variables. Save your program as **Question3_J2023** . Copy and paste the program code into **part 3(a)** in the evidence document. **(b) (i)** Study the pseudocode function `PushAnimal()` : <span class="part-marks">3 marks</span> ``` FUNCTION PushAnimal(DataToPush : STRING) RETURNS BOOLEAN IF AnimalTopPointer = 20 THEN RETURN FALSE ELSE Animal[AnimalTopPointer] DataToPush AnimalTopPointer AnimalTopPointer + 1 RETURN TRUE ENDIF ENDFUNCTION ``` Write program code for the function `PushAnimal()` Save your program. Copy and paste the program code into **part 3(b)(i)** in the evidence document. #### (ii) Study the pseudocode function `PopAnimal()` : <span class="part-marks">3 marks</span> ``` FUNCTION PopAnimal() RETURNS STRING DECLARE ReturnData : STRING IF AnimalTopPointer = 0 THEN RETURN "" ELSE ReturnData Animal[AnimalTopPointer - 1] AnimalTopPointer AnimalTopPointer - 1 RETURN ReturnData ENDIF ENDFUNCTION ``` Write program code to declare the function `PopAnimal()` Save your program. Copy and paste the program code into **part 3(b)(ii)** in the evidence document. #### (iii) The procedure `ReadData()` : <span class="part-marks">5 marks</span> - reads the animal names from the file `AnimalData.txt` - uses `PushAnimal()` to insert each name onto the stack - uses appropriate exception handling if the file does not exist. Write program code for the procedure `ReadData()` Save your program. Copy and paste the program code into **part 3(b)(iii)** in the evidence document. #### (iv) The function `PushColour()` performs the same actions as `PushAnimal()` but inserts an item into `Colour` . <span class="part-marks">2 marks</span> The function `PopColour()` performs the same actions as `PopAnimal()` but removes the next item from `Colour` . Write program code for the functions `PushColour()` and `PopColour()` Save your program. Copy and paste the program code into **part 3(b)(iv)** in the evidence document. #### (v) Amend the procedure `ReadData()` so that it also: - reads the colours from the text file `ColourData.txt` - uses `PushColour()` to insert each colour onto the stack - uses appropriate exception handling if the file does not exist. Save your program. Copy and paste the program code into **part 3(b)(v)** in the evidence document. ### (c) The procedure `OutputItem()` : <span class="part-marks">2 marks</span> - pops the next item from both `Animal` and `Colour` - outputs the colour and animal on one line, for example `"black horse"` If there is no data in `Colour` : - the animal is pushed back onto `Animal` - `"No colour"` is output. If there is no data in `Animal` : - the colour is pushed back onto `Colour` - `"No animal"` is output. Write program code for the procedure `OutputItem()` Save your program. Copy and paste the program code into **part 3(c)** in the evidence document. ### (d) The main program: <span class="part-marks">5 marks</span> - calls the procedure `ReadData()` - calls `OutputItem()` **four** times. #### (i) Write program code for the main program. <span class="part-marks">1 mark</span> Save your program. Copy and paste the program code into **part 3(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 3(d)(ii)** in the evidence document.
Show mark scheme

3(a) [3 marks]

1 mark each (Global) Animal array (with 20 string elements) (Global) Colour array (with 10 string elements) (Global) AnimalTopPointer and ColourTopPointer initialised to 0 Example program code: public static String[] Animal = new String[20]; public static String[] Colour = new String[10]; public static Integer AnimalTopPointer = 0; public static Integer ColourTopPointer = 0; VB.NET Dim Animal(0 to 19) As String Dim Colour(0 to 9) As String Dim AnimalTopPointer As Integer = 0 Dim ColourTopPointer As Integer = 0 Python Animal = [] #20 elements Colour = [] #10 elements global AnimalTopPointer global ColourTopPointer AnimalTopPointer = 0 ColourTopPointer = 0

3(b)(i)

else: Animal.append(DataToPush) AnimalTopPointer +=1 return True

3(b)(ii)

Python def PopAnimal(): global AnimalTopPointer global ColourTopPointer if AnimalTopPointer == 0: return "" else: ReturnData = Animal[AnimalTopPointer - 1] AnimalTopPointer -=1 return ReturnData

3(b)(iii)

Python def ReadData(): try: global AnimalTopPointer global ColourTopPointer AnimalFile = open("AnimalData.txt", 'r') for Line in AnimalFile: PushAnimal(Line) AnimalFile.close() except IOError: print("Could not find file")

3(b)(iv)

End Function Function PopColour() Dim ReturnData As String If ColourTopPointer = 0 Then Return "" Else ReturnData = Colour(ColourTopPointer - 1) ColourTopPointer = ColourTopPointer - 1 Return ReturnData End If End Function Python def PushColour(DataToPush): global AnimalTopPointer global ColourTopPointer if ColourTopPointer == 10: return False else: Colour.append(DataToPush) ColourTopPointer +=1 return True def PopColour(): global AnimalTopPointer global ColourTopPointer if ColourTopPointer == 0: return "" else: ReturnData = Colour[ColourTopPointer - 1] ColourTopPointer -=1 return ReturnData

3(b)(v)

Loop AnimalFileReader.Close() Dim ColourFile As String = "ColourData.txt" Dim ColourFileReader As New System.IO.StreamReader(ColourFile) Do Until ColourFileReader.EndOfStream PushColour(ColourFileReader.ReadLine()) Loop ColourFileReader.Close() Catch ex As Exception Console.WriteLine("Invalid file") End Try End Sub Python def ReadData(): try: global AnimalTopPointer global ColourTopPointer AnimalFile = open("AnimalData.txt", 'r') for Line in AnimalFile: PushAnimal(Line) AnimalFile.close() ColourFile = open("ColourData.txt", 'r') for Line in ColourFile: PushColour(Line) ColourFile.close() except IOError: print("Could not find file")

3(c)

Else If Animalreturned = "" Then Console.WriteLine("No animal") PushColour(ColourReturned) Else Console.WriteLine("A " & ColourReturned & " " & Animalreturned) End If End If End Sub Python def OutputItem(): global AnimalTopPointer global ColourTopPointer ColourReturned = PopColour() AnimalReturned = PopAnimal() if ColourReturned == "": print("No colour") PushAnimal(AnimalReturned) else: if AnimalReturned == "": print("No animal") PushColour(ColourReturned) else: print(ColourReturned, AnimalReturned)

3(d)(i) [1 mark]

1 mark for Calling ReadData() and calling OutputItem() 4 times Example program code: public static void main(String args[]){ ReadData(); OutputItem(); OutputItem(); OutputItem(); OutputItem(); VB.NET Sub Main() ReadData() OutputItem() OutputItem() OutputItem() OutputItem() End Sub Python ReadData() OutputItem() OutputItem() OutputItem() OutputItem()

3(d)(ii) [1 mark]

1 mark for output

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

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

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