Skip to content

10.2 Arrays

AS Level · 56 questions found

  • Array terminology: index, upper and lower bound
  • Choose 1D or 2D array for a given task; write pseudocode for both
  • Bubble sort in pseudocode; linear search in pseudocode
Q2
Oct/Nov 2025 Paper 2 v1

Data is a global 1D array containing 30 elements of type STRING

An algorithm will output:

  • all non-blank elements (elements that do not contain an empty string)

  • the final total of the number of elements output.

Complete the program flowchart to represent the algorithm:

START

END 5 marks

Data is a global 1D array containing 30 elements of type STRING An algorithm will output: - all non-blank elements (elements that do not contain an empty string) - the final total of the number of elements output. Complete the program flowchart to represent the algorithm: START END <span class="part-marks">5 marks</span>
Show mark scheme

2 Alternative solution Checking for empty string first

Q4
Oct/Nov 2025 Paper 2 v1

A program contains a global 1D array Number consisting of 20 elements of type REAL

A procedure Store() will input a sequence of up to 20 real values, one value at a time. These values will be assigned to elements of the array using four steps:

Step 1: store the first value in the sequence in the first element of the array Step 2: check each subsequent value input. If this value is larger than the previous value input, then assign the value to the next array element, otherwise go to step 4 Step 3: repeat from step 2 unless the array is full Step 4: output the count of the number of values stored in the array together with a suitable message.

(a) Complete the pseudocode for Store() 6 marks

All variables used in the algorithm must be declared.

PROCEDURE Store()

ENDPROCEDURE

(b) The requirements of the program change:

  • the number of values in the sequence is unknown, but may be higher than 20

  • the values will need to be accessed by another program as data.

The data will be stored in a text file instead of an array.

(i) Give two benefits of using a text file instead of an array. 2 marks

1

2

(ii) State any change that will need to be made before each value is written to the file. 1 mark

A program contains a global 1D array Number consisting of 20 elements of type REAL A procedure Store() will input a sequence of up to 20 real values, one value at a time. These values will be assigned to elements of the array using four steps: Step 1: store the first value in the sequence in the first element of the array Step 2: check each subsequent value input. If this value is larger than the previous value input, then assign the value to the next array element, otherwise go to step 4 Step 3: repeat from step 2 unless the array is full Step 4: output the count of the number of values stored in the array together with a suitable message. ### (a) Complete the pseudocode for Store() <span class="part-marks">6 marks</span> All variables used in the algorithm must be declared. PROCEDURE Store() ENDPROCEDURE ### (b) The requirements of the program change: - the number of values in the sequence is unknown, but may be higher than 20 - the values will need to be accessed by another program as data. The data will be stored in a text file instead of an array. #### (i) Give two benefits of using a text file instead of an array. <span class="part-marks">2 marks</span> 1 2 #### (ii) State any change that will need to be made before each value is written to the file. <span class="part-marks">1 mark</span>
Show mark scheme

4(a)

Alternative FOR loop example solution: PROCEDURE Store() DECLARE ThisNum, LastNum : REAL DECLARE Index : INTEGER // index to global array DECLARE Count : INTEGER INPUT ThisNum  LastNum ThisNum  Number[1] ThisNum  Count 1 INPUT ThisNum  FOR Index 2 TO 20 IF ThisNum > LastNum THEN  Number[Index] ThisNum  LastNum ThisNum  Count Count + 1 IF Index < 20 THEN INPUT ThisNum ENDIF ELSE BREAK ENDIF NEXT Index OUTPUT Count, " values were stored in the array" ENDPROCEDURE Alternative loop:  Count 1 INPUT ThisNum  FOR Index 2 TO 20 IF ThisNum > Number[Index - 1] THEN  Number[Index] ThisNum  Count Count + 1 IF Index < 20 THEN INPUT ThisNum ENDIF ELSE BREAK ENDIF NEXT Index Mark as follows: 1 Declare local variables as integer, and as real Index ThisNum LastNum 2 Input value and assign to first element 3 Count-controlled loop 4 Count-controlled loop with BREAK if current value greater than previous value 5 ... Assign input value to current element following correct comparison in a loop 6 Final output giving count of elements stored plus message following a reasonable attempt after loop

4(b)(i) [2 marks]

One mark per point: 1 The amount of values stored (in a text file) is not fixed / not limited (other than by secondary storage available) // The amount values stored is not limited to the size of the array 2 The data is stored permanently / non-volatile // Data can be restored / reused without re-entering values

4(b)(ii) [1 mark]

Each (real) value would have to be converted to a string

Q5
Oct/Nov 2025 Paper 2 v1

A program is being designed in pseudocode.

The program contains the following declaration for the global array MyData:

DECLARE MyData : ARRAY[1:10000] OF STRING

A function FindFirst() is written to search the array for a given string and to return the index of the first element where that string is found, or to return –1 if the string is not found.

The function is written in pseudocode as shown:

FUNCTION FindFirst(SearchString : STRING) RETURNS INTEGER DECLARE Index, FoundAt : INTEGER FoundAt –1 FOR Index 1 TO 10000 IF MyData[Index] = SearchString THEN // outer conditional clause IF FoundAt = –1 THEN // inner conditional clause FoundAt Index ENDIF ENDIF NEXT Index RETURN FoundAt ENDFUNCTION

(a) (i) Comment on why the programmer chose –1 as the initial value of FoundAt 1 mark

(ii) Explain the purpose of the outer conditional clause. 1 mark

(iii) The inner conditional clause ensures that only the index of the first matching element, if any, is returned. 1 mark

Explain how this clause works.

(b) The pseudocode does not use the most appropriate loop construct.

(i) Explain why this is not the most appropriate loop construct. 1 mark

(ii) Suggest and justify a more appropriate loop construct that could be used. 2 marks

Construct

Justification

A program is being designed in pseudocode. The program contains the following declaration for the global array MyData: DECLARE MyData : ARRAY[1:10000] OF STRING A function FindFirst() is written to search the array for a given string and to return the index of the first element where that string is found, or to return –1 if the string is not found. The function is written in pseudocode as shown: FUNCTION FindFirst(SearchString : STRING) RETURNS INTEGER DECLARE Index, FoundAt : INTEGER FoundAt –1 FOR Index 1 TO 10000 IF MyData[Index] = SearchString THEN // outer conditional clause IF FoundAt = –1 THEN // inner conditional clause FoundAt Index ENDIF ENDIF NEXT Index RETURN FoundAt ENDFUNCTION ### (a) (i) Comment on why the programmer chose –1 as the initial value of FoundAt <span class="part-marks">1 mark</span> #### (ii) Explain the purpose of the outer conditional clause. <span class="part-marks">1 mark</span> #### (iii) The inner conditional clause ensures that only the index of the first matching element, if any, is returned. <span class="part-marks">1 mark</span> Explain how this clause works. ### (b) The pseudocode does not use the most appropriate loop construct. #### (i) Explain why this is not the most appropriate loop construct. <span class="part-marks">1 mark</span> #### (ii) Suggest and justify a more appropriate loop construct that could be used. <span class="part-marks">2 marks</span> Construct Justification
Show mark scheme

5(a)(i) [1 mark]

It is a value that is invalid as an (array) index // not in the range of valid (index) values

5(a)(ii) [1 mark]

To test whether the current element / value at index matches the given / search string / data / parameter

5(a)(iii) [1 mark]

The value of is only updated to the (current) index if it currently FoundAt stores the initial value / -1 // is not updated when it currently stores any other value than -1 FoundAt

5(b)(i) [1 mark]

The loop continues after the (first instance) of the search value / string / matching element has been found Comparisons/tests continue to be made even if the search value / string / matching element has been found

5(b)(ii) [2 marks]

One mark per point Construct: A conditional loop Justification: The loop / search can be terminated as soon as the (first occurrence of) / required value / required SearchString string / matching element is found

Q8
Oct/Nov 2025 Paper 2 v1

A program is being developed to manage student book loans from a college library. Students may borrow up to five books at a time from the library.

The programmer has defined a record type to define each loan.

The record data items are:

Data item Data type Comment
StudentID STRING the unique ID of the student who has borrowed the book
BookID STRING the unique ID of the book being borrowed
OnLoan BOOLEAN TRUE if the book has not been returned

The programmer has defined a global array Loan to store 5000 loan records.

There are more elements in the array than books in the library. Unused elements have the StudentID set to an empty string. These may occur anywhere in the array.

The programmer has defined the first program module:

Module Description
OKToBorrow()
called with a parameter of type STRING representing a
StudentID

search the array for loan records for the specified student

output a suitable message to say whether the student may, or
may not, borrow another book

(a) Write efficient pseudocode for the module OKToBorrow() 7 marks

(b) A second module is defined: 8 marks

Module Description
ReturnBook()
called with two parameters of type STRING representing a
StudentID and a BookID

searches the array for the relevant loan record

when found, sets OnLoan to FALSE and returns TRUE

if a loan record is not found, or the book has already been
returned, then returns FALSE

Write efficient pseudocode for the module ReturnBook()

Assume that each student is only allowed to borrow each book only once. That means that there will be no more than one loan record for a given combination of student and book.

(c) It is decided to introduce a system of fines for books that have been borrowed for too long. 2 marks

Two new requirements are defined:

  1. Each loan has a maximum length, represented as a number of days.
  2. Each book in the library will be assigned one of three categories. Each category has a different maximum loan length.

Record structure and program design changes are needed to meet these two requirements.

Outline the changes that are necessary to meet the two requirements.

A program is being developed to manage student book loans from a college library. Students may borrow up to five books at a time from the library. The programmer has defined a record type to define each loan. The record data items are: |Data item|Data type|Comment| |---|---|---| |StudentID|STRING|the unique ID of the student who has borrowed the book| |BookID|STRING|the unique ID of the book being borrowed| |OnLoan|BOOLEAN|TRUE if the book has not been returned| The programmer has defined a global array Loan to store 5000 loan records. There are more elements in the array than books in the library. Unused elements have the StudentID set to an empty string. These may occur anywhere in the array. The programmer has defined the first program module: |Module|Description| |---|---| |OKToBorrow()|• <br>called with a parameter of type STRING representing a<br>StudentID<br>• <br>search the array for loan records for the specified student<br>• <br>output a suitable message to say whether the student may, or<br>may not, borrow another book| ### (a) Write efficient pseudocode for the module OKToBorrow() <span class="part-marks">7 marks</span> ### (b) A second module is defined: <span class="part-marks">8 marks</span> |Module|Description| |---|---| |ReturnBook()|• <br>called with two parameters of type STRING representing a<br>StudentID and a BookID<br>• <br>searches the array for the relevant loan record<br>• <br>when found, sets OnLoan to FALSE and returns TRUE<br>• <br>if a loan record is not found, or the book has already been<br>returned, then returns FALSE| Write efficient pseudocode for the module ReturnBook() Assume that each student is only allowed to borrow each book only once. That means that there will be no more than one loan record for a given combination of student and book. ### (c) It is decided to introduce a system of fines for books that have been borrowed for too long. <span class="part-marks">2 marks</span> Two new requirements are defined: 1. Each loan has a maximum length, represented as a number of days. 2. Each book in the library will be assigned one of three categories. Each category has a different maximum loan length. Record structure and program design changes are needed to meet these two requirements. Outline the changes that are necessary to meet the two requirements.
Show mark scheme

8(a) [7 marks]

Example solution: PROCEDURE OKToBorrow(ThisStudentID : STRING) DECLARE Index, Count : INTEGER CONSTANT Max = 5  Count 0  Index 1 / 0 WHILE Index <= 5000 / Index <= 4999 AND Count < Max IF Loan[Index].StudentID = ThisStudentID AND __ Loan[Index].OnLoan = TRUE THEN  Count Count + 1 ENDIF  Index Index + 1 ENDWHILE IF Count < Max THEN OUTPUT "Student may borrow another book" ELSE OUTPUT "Student may not borrow another book" ENDIF ENDPROCEDURE Mark as follows: 1 Procedure heading, parameter and ending 2 Loop through all elements in array Loan 3 ... terminating if reached Max 4 Test for correct field in a loop StudentID 5 ... and that in a loop OnLoan = TRUE ... if so, then increment in a loop Count 6 Output an appropriate message in both cases after the loop

8(b)

WHILE Index < 5001 AND NOT Found IF Loan[Index].StudentID = ThisStudentID AND __ Loan[Index].BookID = ThisBookID THEN  Found TRUE IF Loan[Index].OnLoan = FALSE THEN // Already returned  OK FALSE ELSE  Loan[Index].OnLoan FALSE // Mark as returned now ENDIF ENDIF  Index Index + 1 ENDWHILE RETURN Found AND OK ENDFUNCTION

8(c) [2 marks]

Award marks for reference to following design features: Change to existing Record: 1 Store date due back as a new data item / in the loan record 2 Store date of loan and the loan length category as new data items / in the loan record Max 1 New Record 3 New Records with Category (and Loan length field) Change to Program: 4 (Use the loan length category of a book to) calculate the date due date 5 Compare due date with today’s date (to check if overdue / to calculate fine) 6 Map loan length category to length of loan / date due back Max 1 Max 2 marks

Q2
Oct/Nov 2025 Paper 2 v2

Data is a global 1D array containing 20 elements of type REAL

An algorithm will:

  • input a sequence of real values, one at a time

  • assign each value to consecutive array elements, starting from index 1

  • end when the value 99.9 is input, or all 20 elements have been assigned (the value 99.9 must not be stored in the array).

Complete the program flowchart to represent the algorithm:

START

END 5 marks

Data is a global 1D array containing 20 elements of type REAL An algorithm will: - input a sequence of real values, one at a time - assign each value to consecutive array elements, starting from index 1 - end when the value 99.9 is input, or all 20 elements have been assigned (the value 99.9 must not be stored in the array). Complete the program flowchart to represent the algorithm: START END <span class="part-marks">5 marks</span>
Show mark scheme

2 Alternative solution:

Q4
Oct/Nov 2025 Paper 2 v2

A quiz has nine questions. There are:

  • five easy questions each worth 3 points

  • four hard questions each worth 5 points.

At the end of the quiz the points for each correctly answered question are added to give a total score.

A check is made to test that the total score is valid using a 1D array CheckTotal of type BOOLEAN. Each index value of the array represents a possible total score. The corresponding element value is TRUE if the index value represents a valid total score and FALSE otherwise.

The first nine rows of the array are:

Index
value
Element
value
Comment
0 TRUE valid total score (no correct answers)
1 FALSE invalid total score
2 FALSE invalid total score
3 TRUE valid total score (one 3-point question correct)
4 FALSE invalid total score
5 TRUE valid total score (one 5-point question correct)
6 TRUE valid total score (two 3-point questions correct)
7 FALSE invalid total score
8 TRUE valid total score (one 3-point question and one 5-point question correct)

For example, a total score of 6 points is valid; the value of the array element at index value 6 is TRUE

(a) Write pseudocode to declare CheckTotal and to set all elements of the array to FALSE All variables used must be declared. 4 marks

(b) The pseudocode represents an algorithm to set the appropriate elements of the array to TRUE Complete the pseudocode: 5 marks

DECLARE EasyQ, HardQ : INTEGER

FOR EasyQ ______ TO 15 STEP

FOR HardQ 0 TO ______ STEP

CheckTotal[______] TRUE

NEXT HardQ

NEXT EasyQ

(c) The array elements have been assigned the required values. 4 marks

A module ValidateScore() will take an integer value representing a total score as a parameter. It will return TRUE if the total score is valid, or FALSE if it is not valid.

Describe the algorithm for ValidateScore() using four steps.

Do not use pseudocode in your answer.

Step 1

Step 2

Step 3

Step 4

A quiz has nine questions. There are: - five easy questions each worth 3 points - four hard questions each worth 5 points. At the end of the quiz the points for each correctly answered question are added to give a total score. A check is made to test that the total score is valid using a 1D array CheckTotal of type BOOLEAN. Each index value of the array represents a possible total score. The corresponding element value is TRUE if the index value represents a valid total score and FALSE otherwise. The first nine rows of the array are: |Index<br>value|Element<br>value|Comment| |---|---|---| |0|TRUE|valid total score (no correct answers)| |1|FALSE|invalid total score| |2|FALSE|invalid total score| |3|TRUE|valid total score (one 3-point question correct)| |4|FALSE|invalid total score| |5|TRUE|valid total score (one 5-point question correct)| |6|TRUE|valid total score (two 3-point questions correct)| |7|FALSE|invalid total score| |8|TRUE|valid total score (one 3-point question and one 5-point question correct)| For example, a total score of 6 points is valid; the value of the array element at index value 6 is TRUE ### (a) Write pseudocode to declare CheckTotal and to set all elements of the array to FALSE All variables used must be declared. <span class="part-marks">4 marks</span> ### (b) The pseudocode represents an algorithm to set the appropriate elements of the array to TRUE Complete the pseudocode: <span class="part-marks">5 marks</span> DECLARE EasyQ, HardQ : INTEGER FOR EasyQ ______ TO 15 STEP FOR HardQ 0 TO ______ STEP CheckTotal[______] TRUE NEXT HardQ NEXT EasyQ ### (c) The array elements have been assigned the required values. <span class="part-marks">4 marks</span> A module ValidateScore() will take an integer value representing a total score as a parameter. It will return TRUE if the total score is valid, or FALSE if it is not valid. Describe the algorithm for ValidateScore() using four steps. Do not use pseudocode in your answer. Step 1 Step 2 Step 3 Step 4
Show mark scheme

4(a) [4 marks]

Example solution: DECLARE CheckTotal : ARRAY [0:35] OF BOOLEAN DECLARE Index : INTEGER  FOR Index 0 TO 35  CheckTotal[Index] FALSE NEXT Index Mark as follows: MP1 Declaration of array CheckTotal MP2 Declaration of a loop counter MP3 Loop – with correct syntax and number of iterations MP4 Assignment of array element to FALSE

4(b) [5 marks]

DECLARE EasyQ, HardQ : INTEGER 0 3  FOR EasyQ TO 15 STEP MP1 MP2 20 5  FOR HardQ 0 TO STEP MP3 MP4 HardQ + EasyQ  CheckTotal[ ] TRUE MP5 NEXT HardQ NEXT EasyQ Mark as follows: One mark per gap (boldened)

4(c) [4 marks]

MP1 Check that the parameter value is in the range 0 to 35 MP2 ... and if not, return FALSE MP3 Use the parameter value as the index to array CheckTotal MP4 Return the value from given index position

Q8
Oct/Nov 2025 Paper 2 v2

A program is being developed to manage student book loans from a college library.

The programmer has defined a record type to define each loan.

The data items are:

Data item Data type Comment
StudentID STRING the unique ID of the student who has borrowed the book
BookID STRING the unique ID of the book being borrowed
OnLoan BOOLEAN TRUE if the book has not been returned

The programmer has defined a global array Loan to store 7000 loan records.

There are more elements in the array than books in the library. Unused elements have the StudentID set to an empty string. These may occur anywhere in the array.

The programmer has defined a program module:

Module Description
CountLoans()
called with a parameter of type STRING representing a
StudentID

counts the number of books currently on loan to the
specified student

counts the number of books that the student has already
returned

output both counts together with a suitable message

(a) Write pseudocode for module CountLoans() 7 marks

(b) As a reminder, a global array Loan stores 7000 loan records with data items for each loan record: 7 marks

Data item Data type Comment
StudentID STRING the unique ID of the student who has borrowed the book
BookID STRING the unique ID of the book being borrowed
OnLoan BOOLEAN TRUE if the book has not been returned

A new module is defined:

Module Description
NewLoan()
called with two parameters of type STRING representing a
StudentID and a BookID

searches the array for an unused loan record

if found, updates the loan record and returns TRUE, otherwise
returns FALSE

Write efficient pseudocode for NewLoan()

(c) When a book is returned, the loan record will have its OnLoan data set to FALSE A new procedure Archive() will mark these records as unused after first saving them for future reference. 2 marks

Explain how these records can be saved for future reference.

(d) It is decided to extend the program so that a new module Reminder() will send an email to the student three days before the book is due to be returned. 2 marks

Outline the changes that will need to be made to the data stored and how this data will be used to generate the reminder email.

Data

Use

A program is being developed to manage student book loans from a college library. The programmer has defined a record type to define each loan. The data items are: |Data item|Data type|Comment| |---|---|---| |StudentID|STRING|the unique ID of the student who has borrowed the book| |BookID|STRING|the unique ID of the book being borrowed| |OnLoan|BOOLEAN|TRUE if the book has not been returned| The programmer has defined a global array Loan to store 7000 loan records. There are more elements in the array than books in the library. Unused elements have the StudentID set to an empty string. These may occur anywhere in the array. The programmer has defined a program module: |Module|Description| |---|---| |CountLoans()|• <br>called with a parameter of type STRING representing a<br>StudentID<br>• <br>counts the number of books currently on loan to the<br>specified student<br>• <br>counts the number of books that the student has already<br>returned<br>• <br>output both counts together with a suitable message| ### (a) Write pseudocode for module CountLoans() <span class="part-marks">7 marks</span> ### (b) As a reminder, a global array Loan stores 7000 loan records with data items for each loan record: <span class="part-marks">7 marks</span> |Data item|Data type|Comment| |---|---|---| |StudentID|STRING|the unique ID of the student who has borrowed the book| |BookID|STRING|the unique ID of the book being borrowed| |OnLoan|BOOLEAN|TRUE if the book has not been returned| A new module is defined: |Module|Description| |---|---| |NewLoan()|• <br>called with two parameters of type STRING representing a<br>StudentID and a BookID<br>• <br>searches the array for an unused loan record<br>• <br>if found, updates the loan record and returns TRUE, otherwise<br>returns FALSE| Write efficient pseudocode for NewLoan() ### (c) When a book is returned, the loan record will have its OnLoan data set to FALSE A new procedure Archive() will mark these records as unused after first saving them for future reference. <span class="part-marks">2 marks</span> Explain how these records can be saved for future reference. ### (d) It is decided to extend the program so that a new module Reminder() will send an email to the student three days before the book is due to be returned. <span class="part-marks">2 marks</span> Outline the changes that will need to be made to the data stored and how this data will be used to generate the reminder email. Data Use
Show mark scheme

8(a) [7 marks]

Example solution: PROCEDURE CountLoans(ThisStudentID : STRING) DECLARE Index, LCount, RCount : INTEGER  LCount 0  RCount 0  FOR Index 1 TO 7000 IF Loan[Index].StudentID = ThisStudentID THEN IF Loan[Index].OnLoan = FALSE THEN  RCount RCount + 1 ELSE  LCount LCount + 1 ENDIF ENDIF NEXT Index OUTPUT "Student has ", LCount, " books on loan" OUTPUT "and has returned ", RCount, " books" ENDPROCEDURE Mark as follows: MP1 Declaration of Index and two count variables MP2 Loop for 7000 iterations MP3 references an indexed data item with correct .dot notation Index MP4 Attempt to compare the field = parameter in a loop StudentID MP5 Test of the field and correct logic for both outcomes OnLoan MP6 Both count variables initialised and increment appropriate count in a loop MP7 Output includes both counts with a suitable message

8(b) [7 marks]

Example solution: FUNCTION NewLoan(ThisStudentID, ThisBookID : STRING) __ RETURNS BOOLEAN DECLARE Index : INTEGER DECLARE IsStored : BOOLEAN CONSTANT Blank = ""  Index 1  IsStored FALSE WHILE Index <= 7000 AND NOT IsStored IF Loan[Index].StudentID = Blank THEN  Loan[Index].StudentID ThisStudentID  Loan[Index].BookID ThisBookID  Loan[Index].OnLoan TRUE  IsStored TRUE ENDIF  Index Index + 1 ENDWHILE RETURN IsStored ENDFUNCTION Mark as follows: MP1 Loop through 7000 elements in array – correct loop structure Loan MP2 or until the first unused element is found // Correct inside a RETURN loop FOR MP3 Correct use of the indexed dot notation MP4 Test if record is unused ( in a loop .StudentID = "") MP5 Two item assignment statements correct MP6 assigned TRUE Loan[Index].OnLoan MP7 Correct logic to return in both cases (position found / no BOOLEAN position available) Alternative solution: loop only (no ‘found’ mechanism)  FOR Index 1 TO 7000 IF Loan[Index].StudentID = Blank THEN  Loan[Index].StudentID ThisStudentID  Loan[Index].BookID ThisBookID  Loan[Index].OnLoan TRUE RETURN TRUE ENDIF NEXT RETURN FALSE

8(c) [2 marks]

MP1 Save to/Open a (text) file MP2 Single line – form a string with separator characters and write to the file // Multiple lines

  • write each data item to a separate line in the file

8(d) [2 marks]

Additional date(s) solution MP1 Store the return date of each loan // the start date and the loan period MP2 Algorithm will do a calculation involving the MP1 data item(s) OR The student email address solution MP3 Store the student email address MP4 In order to send the email // the student is alerted to return the book Max 2

Q4
Oct/Nov 2025 Paper 2 v3

A program contains a global 1D array Data containing 20 elements of type INTEGER

A global string NumString represents a sequence of three-digit numbers, separated by commas. For example:

"101,456,219,754,328"

The string contains at least four three-digit numbers. The total number of three-digit numbers in the string is unknown.

A procedure Store() will:

  • extract one three-digit number at a time from NumString

  • convert each of the three-digit numbers extracted to an integer and assign this to the next array element, starting from index 1

  • end when all three-digit numbers have been stored, or when the array is full.

Complete the pseudocode for Store()

All local variables used must be declared.

PROCEDURE Store()

ENDPROCEDURE 6 marks

A program contains a global 1D array Data containing 20 elements of type INTEGER A global string NumString represents a sequence of three-digit numbers, separated by commas. For example: "101,456,219,754,328" The string contains at least four three-digit numbers. The total number of three-digit numbers in the string is unknown. A procedure Store() will: - extract one three-digit number at a time from NumString - convert each of the three-digit numbers extracted to an integer and assign this to the next array element, starting from index 1 - end when all three-digit numbers have been stored, or when the array is full. Complete the pseudocode for Store() All local variables used must be declared. PROCEDURE Store() ENDPROCEDURE <span class="part-marks">6 marks</span>
Show mark scheme

4 Alternative Solution extracting one character at a time and testing for comma PROCEDURE Store()

DECLARE Index, Position : INTEGER DECLARE SubString : STRING Decalre ThisCharacter : CHAR  Index 1  Position 0  SubString "" WHILE Index <= 20 AND Position <= LENGTH(NumString)  Charcter MID(NumString, Position, 1) IF Character = ','  Data[Index] STR_TO_NUM(SubString)  Index Index + 1  SubString "" ELSE  SubString SubString & Character ENDIF  Position Position + 1 ENDWHILE  Data[Index] STR_TO_NUM(SubString) //last 3 digit string ENDPROCEDURE Mark as follows: 1 Declare all variables used 2 Conditional loop while end of string not reached 3 ... and array not full 4 Correct extraction and use of a character from in a loop NumString 5 Test for comma in a loop 6 If true convert substring to number … and store in array and set to and increment Data SubString "" Index 7 Otherwise concatenate next character from to end of NumString Substring Max 6

Q8
Oct/Nov 2025 Paper 2 v3

A program is being developed to manage student book loans from a college library.

The programmer has defined a record type to define each loan.

The data items are:

Data item Data type Comment
StudentID STRING the unique ID of the student who has borrowed
the book

The first three characters of a StudentID
represent a tutor ID. Each student has one tutor.
BookID STRING the unique ID of the book being borrowed
OnLoan BOOLEAN TRUE if the book has not been returned

The programmer has defined a global array Loan to store 8000 loan records.

There are more elements in the array than books in the library. Unused elements have the StudentID set to an empty string. These may occur anywhere in the array.

The programmer has defined a program module:

Module Description
LoanStatus()
called with two parameters of type STRING representing a
StudentID and a BookID

outputs a message saying whether a given loan has been
returned or not

outputs a warning message if a record of the given loan is
not found

(a) Write efficient pseudocode for the module LoanStatus() 8 marks

Assume that each combination of StudentID and BookID can occur only once.

(b) A second module is defined: 7 marks

Module Description
LoansPerTutor()
called with a parameter of type STRING representing
a tutor ID (as a reminder, the first three characters of
a StudentID represent a tutor ID)

returns an integer value representing the number of
books currently on loan to students who have the
given tutor

Reminder: unused elements have the StudentID set to an empty string. These may occur anywhere in the array.

Write pseudocode for the module LoansPerTutor()

(c) It is decided to mark as unused all records for book loans that have been returned. The data for these records will first be written to a new text file for archive purposes.

(i) The archive program will automatically generate a meaningful filename each time it is run. 2 marks

Outline a meaningful format to use for the filename.

(ii) There is a problem that will need to be overcome before the data items can be written to a text file. 1 mark

As a reminder, the data items are:

Data item Data type Comment
StudentID STRING the unique ID of the student who has borrowed the
book
The first three characters of a StudentID represent
a tutor ID. Each student has one tutor.
BookID STRING the unique ID of the book being borrowed
OnLoan BOOLEAN TRUE if the book has not been returned

Explain the problem.

(iii) One way of storing the data items in a text file is to store each data item on a separate line. 2 marks

Identify one benefit and one drawback of this way of storing the data.

Benefit

Drawback

A program is being developed to manage student book loans from a college library. The programmer has defined a record type to define each loan. The data items are: |Data item|Data type|Comment| |---|---|---| |StudentID|STRING|the unique ID of the student who has borrowed<br>the book<br> <br>The first three characters of a StudentID<br>represent a tutor ID. Each student has one tutor.| |BookID|STRING|the unique ID of the book being borrowed| |OnLoan|BOOLEAN|TRUE if the book has not been returned| The programmer has defined a global array Loan to store 8000 loan records. There are more elements in the array than books in the library. Unused elements have the StudentID set to an empty string. These may occur anywhere in the array. The programmer has defined a program module: |Module|Description| |---|---| |LoanStatus()|• <br>called with two parameters of type STRING representing a<br>StudentID and a BookID<br>• <br>outputs a message saying whether a given loan has been<br>returned or not<br>• <br>outputs a warning message if a record of the given loan is<br>not found| ### (a) Write efficient pseudocode for the module LoanStatus() <span class="part-marks">8 marks</span> Assume that each combination of StudentID and BookID can occur only once. ### (b) A second module is defined: <span class="part-marks">7 marks</span> |Module|Description| |---|---| |LoansPerTutor()|• <br>called with a parameter of type STRING representing<br>a tutor ID (as a reminder, the first three characters of<br>a StudentID represent a tutor ID)<br>• <br>returns an integer value representing the number of<br>books currently on loan to students who have the<br>given tutor| Reminder: unused elements have the StudentID set to an empty string. These may occur anywhere in the array. Write pseudocode for the module LoansPerTutor() ### (c) It is decided to mark as unused all records for book loans that have been returned. The data for these records will first be written to a new text file for archive purposes. #### (i) The archive program will automatically generate a meaningful filename each time it is run. <span class="part-marks">2 marks</span> Outline a meaningful format to use for the filename. #### (ii) There is a problem that will need to be overcome before the data items can be written to a text file. <span class="part-marks">1 mark</span> As a reminder, the data items are: |Data item|Data type|Comment| |---|---|---| |StudentID|STRING|the unique ID of the student who has borrowed the<br>book<br>The first three characters of a StudentID represent<br>a tutor ID. Each student has one tutor.| |BookID|STRING|the unique ID of the book being borrowed| |OnLoan|BOOLEAN|TRUE if the book has not been returned| Explain the problem. #### (iii) One way of storing the data items in a text file is to store each data item on a separate line. <span class="part-marks">2 marks</span> Identify one benefit and one drawback of this way of storing the data. Benefit Drawback
Show mark scheme

8(a) [8 marks]

Example solution: PROCEDURE LoanStatus(ThisStudentID, ThisBookID : STRING) DECLARE Index : INTEGER DECLARE Found : BOOLEAN  Index 1 / 0  Found FALSE WHILE Index <= 8000 / 7999 AND NOT Found IF Loan[Index].StudentID = ThisStudentID AND Loan[Index].BookID = ThisBookID THEN IF Loan[Index].OnLoan = FALSE THEN OUTPUT "Loan has been returned." ELSE OUTPUT "Loan has not been returned." ENDIF  Found TRUE ENDIF  Index Index + 1 ENDWHILE IF NOT Found THEN OUTPUT "Warning - Loan not found." ENDIF ENDPROCEDURE Mark as follows: 1 Procedure heading, parameters and ending 2 Loop through all elements in array Loan 3 ... or until record loan is found 4 Test for correct in a loop StudentID 5 ... and correct BookID 6 ... check data item OnLoan 7 ... and output both messages as appropriate regarding book loan status once 8 If no matching loan found, Output 'not found' after the loop

8(b) [7 marks]

Example solution: FUNCTION LoansPerTutor(TutorID : STRING) RETURNS INTEGER DECLARE Index, Count : INTEGER  Count 0  FOR Index 1 / 0 TO 8000 / 7999 IF LEFT(Loan[Index].StudentID, 3) = TutorID AND Loan[Index].OnLoan = TRUE THEN  Count Count + 1 ENDIF NEXT Index RETURN Count ENDFUNCTION Mark as follows: 1 Initialise local integer for Count 2 Loop through all elements in the array Loan 3 Attempt at referencing a data item in a loop 4 Extract from in a loop TutorID Loan[Index].StudentID 5 Test for Matching Tutor AND test if the book has been returned using correct dot notation in a loop 6 ... if true then increment in a loop Count 7 Return count

8(c)(i) [2 marks]

One mark per point: 1 Include (a suffix string based on) the date of the archive / the next number in sequence 2 Concatenate with a root filename such as 'Archive'

8(c)(ii) [1 mark]

Boolean data cannot be written to a text file // is not a string // OnLoan will have to be converted to text OnLoan

8(c)(iii) [2 marks]

One mark per point: Benefit: Algorithm to store / extract a record is easier // unpacking of data is not required // No need for string concatenation Drawback: More file accesses needed (to read / write a complete record)

Q4
May/Jun 2025 Paper 2 v2

An algorithm will:

  • input 100 integer values, one value at a time

  • store the first value input into the first location of the array Number

  • store the next input value in the next unused location of the array Number

  • output the contents of Number array in the opposite sequence to that in which the values were input.

Complete the program flowchart to represent the algorithm.

Variable declarations are not required.

START

END 6 marks

An algorithm will: - input 100 integer values, one value at a time - store the first value input into the first location of the array Number - store the next input value in the next unused location of the array Number - output the contents of Number array in the opposite sequence to that in which the values were input. Complete the program flowchart to represent the algorithm. Variable declarations are not required. START END <span class="part-marks">6 marks</span>
Show mark scheme

4 [6 marks]

One mark for each functional group as listed:

  1. Initialise Index used for to either 1 or 0 before first loop Number
  2. Loop 100 times
  3. Input value
  4. Increment array index and store value in array at element Number referenced by array in a loop index
  5. Output loop starts at last element in array Number
  6. Output array element referenced by in a loop Number Index
  7. Output all elements of array once in reverse order Number Max 6
Q7
May/Jun 2025 Paper 2 v2

A program is being developed to implement a customer loyalty scheme for a coffee shop.

Each customer has a unique customer ID starting at 10001 with this value increasing by one each time a new customer joins the loyalty scheme.

For example, the third customer who joins the loyalty scheme is given the customer ID 10003

The loyalty scheme is limited to 1000 customers.

A customer is awarded a loyalty point every time they buy a coffee.

The programmer has decided to use a global 2D array Loyalty of type INTEGER. The array Loyalty is made up of 1000 rows and 2 columns. Each row relates to one customer; column 1 contains the unique customer ID and column 2 contains the number of customer loyalty points.

Rows in the array Loyalty that are not currently being used have the value of Column 1 set to 99999

The array is sorted in ascending order by customer ID.

The programmer has defined a program module:

Module Description
FindCustomer()
called with parameter of type INTEGER representing a customer ID

searches the Loyalty array for this customer ID

the search will stop as soon as the customer ID is found

the search should efficiently deal with the situation when the
customer ID is not stored in the Loyalty array

if the customer ID is found, return an integer value representing the
loyalty points, otherwise return -1

(a) Write efficient pseudocode for module FindCustomer() 8 marks

(b) A customer can claim a free coffee for every 11 loyalty points. 7 marks

The programmer has defined a second program module:

Module Description
PointsReport()
output the customer ID for each customer who has 11 or
more loyalty points

output the average loyalty points for all customers in the
Loyalty array along with an appropriate message

Write efficient pseudocode for module PointsReport()

Assume the array contains the data for at least one customer.

(c) The programmer decides to amend the customer ID; it will be stored as a STRING instead of an INTEGER. This means that the 2D array Loyalty can no longer be used.

(i) Explain why the 2D array Loyalty can no longer be used. 1 mark

(ii) Explain how a 1D array could be used to store both the loyalty points and the amended customer ID. 2 marks

A program is being developed to implement a customer loyalty scheme for a coffee shop. Each customer has a unique customer ID starting at 10001 with this value increasing by one each time a new customer joins the loyalty scheme. For example, the third customer who joins the loyalty scheme is given the customer ID 10003 The loyalty scheme is limited to 1000 customers. A customer is awarded a loyalty point every time they buy a coffee. The programmer has decided to use a global 2D array Loyalty of type INTEGER. The array Loyalty is made up of 1000 rows and 2 columns. Each row relates to one customer; column 1 contains the unique customer ID and column 2 contains the number of customer loyalty points. Rows in the array Loyalty that are not currently being used have the value of Column 1 set to 99999 The array is sorted in ascending order by customer ID. The programmer has defined a program module: |Module|Description| |---|---| |FindCustomer()|• <br>called with parameter of type INTEGER representing a customer ID<br>• <br>searches the Loyalty array for this customer ID<br>• <br>the search will stop as soon as the customer ID is found<br>• <br>the search should efficiently deal with the situation when the<br>customer ID is not stored in the Loyalty array<br>• <br>if the customer ID is found, return an integer value representing the<br>loyalty points, otherwise return -1| ### (a) Write efficient pseudocode for module FindCustomer() <span class="part-marks">8 marks</span> ### (b) A customer can claim a free coffee for every 11 loyalty points. <span class="part-marks">7 marks</span> The programmer has defined a second program module: |Module|Description| |---|---| |PointsReport()|• <br>output the customer ID for each customer who has 11 or<br>more loyalty points<br>• <br>output the average loyalty points for all customers in the<br>Loyalty array along with an appropriate message| Write efficient pseudocode for module PointsReport() Assume the array contains the data for at least one customer. ### (c) The programmer decides to amend the customer ID; it will be stored as a STRING instead of an INTEGER. This means that the 2D array Loyalty can no longer be used. #### (i) Explain why the 2D array Loyalty can no longer be used. <span class="part-marks">1 mark</span> #### (ii) Explain how a 1D array could be used to store both the loyalty points and the amended customer ID. <span class="part-marks">2 marks</span>
Show mark scheme

7(a)

Mark points

  1. Create function header and ending with correct parameter and return type
  2. Check is within range and if not return –1 CustomerID
  3. Conditional loop that halves array search space with each iteration
  4. Check if is stored in current array element in loop CustomerID
  5. Mechanism to end loop if is found in array in a loop CustomerID
  6. Mechanism to end loop if is not in array in a loop CustomerID
  7. If found in array then return correct loyalty points CustomerID
  8. If not in array then return –1 CustomerID

7(b) [7 marks]

Example solution PROCEDURE PointsReport() DECLARE Count : INTEGER DECLARE Index : INTEGER DECLARE Sum : INTEGER DECLARE Average : REAL  Index 1  Count 0  Sum 0 WHILE Loyalty[Index, 1] <> 99999 AND Index <= 1000 IF Loyalty[Index, 2] >= 11 THEN OUTPUT Loyalty[Index, 1] ENDIF  Count Count + 1  Sum Sum + Loyalty[Index, 2]  Index Index + 1 ENDWHILE  Average Sum / Count OUTPUT "The average points of all the customers is ", Average ENDPROCEDURE Mark as follows:

  1. Create procedure header and ending
  2. Declare and initialise , and Index Sum Count
  3. Loop through all elements in array Loyalty
  4. … or terminates when column1 of array equals in a loop Loyalty 99999
  5. Check if loyalty points greater than or equal to in a loop 11
  6. If true output customer ID 7 Sum points and Increment in a loop Count 8 Calculate and output average with an appropriate message Max 7

7(c)(i) [1 mark]

An array can only store data of the same type // An array cannot store data of different types

7(c)(ii) [2 marks]

1 mark for each point

  1. a new (composite) data type / record is defined (that consists of both and ) INTEGER STRING
  2. an array based on this new type is declared Alternative 1 mark for each point
  3. Converting loyalty points to string and concatenating / joining / append with Customer ID
  4. Storing concatenated string in an array of string
Q4
May/Jun 2025 Paper 2 v3

A programmer is developing a new stock control program for a shop owner to produce sales reports.

(a) A text file Sales.txt stores strings representing the number of items sold. 5 marks

The file contains 52 lines, each representing the number of items sold in each week of the year.

For example:

File line number File data 1 "350" 2 "502" 3 "434"

49 "492" 50 "872" 51 "772" 52 "201"

The example shows that 502 items were sold in week 2.

The owner requires a module to output all week numbers where the number of items sold is greater than 500.

Describe an algorithm that produces the required module.

Do not include pseudocode statements in your answer.

(b) Once the program has been completed, it is tested using the walkthrough method. 3 marks

Describe the walkthrough method and explain how it can be used to identify errors.

A programmer is developing a new stock control program for a shop owner to produce sales reports. ### (a) A text file Sales.txt stores strings representing the number of items sold. <span class="part-marks">5 marks</span> The file contains 52 lines, each representing the number of items sold in each week of the year. For example: File line number File data 1 "350" 2 "502" 3 "434" 49 "492" 50 "872" 51 "772" 52 "201" The example shows that 502 items were sold in week 2. The owner requires a module to output all week numbers where the number of items sold is greater than 500. Describe an algorithm that produces the required module. Do not include pseudocode statements in your answer. ### (b) Once the program has been completed, it is tested using the walkthrough method. <span class="part-marks">3 marks</span> Describe the walkthrough method and explain how it can be used to identify errors.
Show mark scheme

4 Sales.txt MP2 Read a line (from the text file)

MP3 Convert the line read (string) to a number MP4 If the number is greater than 500 and then output week number MP5 Increment week number (must have been Initialised … ) MP6 Repeat from step 2 for 52 times // Repeat from step 2 until end of file Max 5

4(b) [3 marks]

MP1 Going through the program a line / statement at a time // doing a dry run // single-stepping ( at run-time with an IDE) // Peer testing/review is carried out MP2 Creating a trace table MP3 Draw up test data // draw up list of inputs with expected output // boundary, normal, abnormal data is used MP4 Errors will be indicated when a variable / output gives an unexpected value MP5 Faults in the logic of the program can be detected // Errors may be indicated by an unexpected path through the program Max 3

Q6
Oct/Nov 2024 Paper 2 v1

A factory produces food items. The items must be used within a certain number of days after their production date. The number of days is known as the shelf life. It is different for each type of item but is always a whole number in the range 1 to 21 (inclusive).

The latest date that an item can be used is called the ‘use-by’ date.

A program is needed to produce labels which show the ‘use-by’ date.

Part of the program is a function GetDate() which will:

  • take two parameters: a production date and a value representing the shelf life

  • return the corresponding ‘use-by’ date.

The program contains a global 1D array DaysInMonth of type integer which stores the number of days in each month (index 1 is January):

Index Value
1 31
2 28
3 31
4 30
11 30
12 31

(a) An algorithm uses the array DaysInMonth to calculate a ‘use-by’ date. An alternative design would involve the use of multiple selection statements. 2 marks

An array-based technique is often used when there is a large number of different values to check and where no pattern exists.

One advantage of using an array-based technique is the speed of execution compared to the use of multiple selection statements.

Give two other advantages of using an array for this type of operation rather than a solution based on multiple selection statements.

1

2

(b) Complete the pseudocode for the function GetDate(). 7 marks

Date functions from the insert should be used in your solution.

FUNCTION GetDate(ProductionDate : DATE, ShelfLife : INTEGER) RETURNS DATE

ENDFUNCTION

A factory produces food items. The items must be used within a certain number of days after their production date. The number of days is known as the shelf life. It is different for each type of item but is always a whole number in the range 1 to 21 (inclusive). The latest date that an item can be used is called the ‘use-by’ date. A program is needed to produce labels which show the ‘use-by’ date. Part of the program is a function GetDate() which will: - take two parameters: a production date and a value representing the shelf life - return the corresponding ‘use-by’ date. The program contains a global 1D array DaysInMonth of type integer which stores the number of days in each month (index 1 is January): |Index|Value| |---|---| |1|31| |2|28| |3|31| |4|30| ||| ||| |11|30| |12|31| ### (a) An algorithm uses the array DaysInMonth to calculate a ‘use-by’ date. An alternative design would involve the use of multiple selection statements. <span class="part-marks">2 marks</span> An array-based technique is often used when there is a large number of different values to check and where no pattern exists. One advantage of using an array-based technique is the speed of execution compared to the use of multiple selection statements. Give two other advantages of using an array for this type of operation rather than a solution based on multiple selection statements. 1 2 ### (b) Complete the pseudocode for the function GetDate(). <span class="part-marks">7 marks</span> Date functions from the insert should be used in your solution. FUNCTION GetDate(ProductionDate : DATE, ShelfLife : INTEGER) RETURNS DATE ENDFUNCTION
Show mark scheme

6(a) [2 marks]

One mark per point: 1 Fewer lines of code are needed 2 The program is simpler/ less complex // Program is easier to design / code / maintain / modify / test / debug 3 Direct access to days in a month / data (using month number as index) // Can use index / month to (directly) access days in month / data Max 2 marks

6(b) [7 marks]

Example Solution FUNCTION GetDate(ProductionDate : DATE, ShelfLife : INTEGER) RETURNS DATE DECLARE NewDate : DATE DECLARE DD, MM, YY, LastDay : INTEGER  DD DAY(ProductionDate)  MM MONTH(ProductionDate)  YY YEAR(ProductionDate)  DD DD + ShelfLife  LastDay DaysInMonth[MM] IF DD > LastDay THEN  MM MM + 1  DD DD – LastDay IF MM = 13 THEN  MM 1  YY YY + 1 ENDIF ENDIF  NewDate SETDATE(DD, MM, YY) RETURN NewDate ENDFUNCTION Mark as follows: 1 Declare three variables of to store , and TYPE INTEGER 2 Correct use of date functions from Insert to extract three integer values representing DD, MM and YY and use/assign to a variable 3 Add parameter to and use / assign result to a variable ShelfLife DD 4 Extract from using as LastDay DaysInMonth MM Index 5 Test for new after end of month / DD DaysInMonth[MM] … and if

: DD DaysInMonth[MM] 6 is incremented by 1 and is set to DD – DaysInMonth[MM] 7 If then increment and set to 1 MM = 13 / MM > 12 8 Use of to assign value to , must have been SETDATE NewDate NewDate delared as a type DATE 9 Return date Max 7 marks

Q8
Oct/Nov 2024 Paper 2 v1

An exam paper has a maximum of 75 marks. One of five pass grades (A to E) is assigned, depending on the mark obtained. The lowest mark for a given grade is known as the grade boundary. For example, if the grade boundary for an A grade is 65 marks, then any candidate who achieves a mark of 65 or above will be awarded an A. A grade of U is awarded for marks below the E grade boundary.

The five grade boundaries are stored in a global 1D array GradeBoundary of type integer.

For example:

Element Value Comment
GradeBoundary[1] 65 The minimum mark for an A grade.
GradeBoundary[2] 57 The minimum mark for a B grade.
GradeBoundary[3] 43 The minimum mark for a C grade.
GradeBoundary[4] 35 The minimum mark for a D grade.
GradeBoundary[5] 27 The minimum mark for an E grade.

A global 2D array Result of type integer contains candidate marks for the exam. Each row relates to one candidate. Column 1 contains the candidate mark and column 2 contains the unique candidate ID.

For example, for the fourth and fifth candidates:

Element Mark
Result[4, 1] 56
Result[5, 1] 54
Element ID
Result[4, 2] 1074832
Result[5, 2] 2573839

There are more rows in the array than candidates who sit the exam. Any unused rows will be at the end of the array.

Candidate papers that are given a mark within two marks of any grade boundary must be checked.

For example, given the values in the example grade boundaries above, any paper that was awarded between 41 and 45 marks (inclusive) would need to be checked.

A program is being written to identify papers that need to be checked.

The programmer has defined the first program module as follows:

Module Description
CheckMark()
called with a parameter of type integer representing a
candidate mark

returns TRUE if the mark is within 2 of any of the five grade
boundaries, otherwise returns FALSE

(a) Write pseudocode for module CheckMark(). 6 marks

(b) A second module is defined: 8 marks

Module Description
CheckAll()
called with a parameter of type integer representing the
number of candidate marks in the Result array

uses CheckMark() to check each candidate mark

for each paper that needs to be checked, write the
corresponding candidate ID on a separate line in a new file
named GRList.txt

outputs a message with a count of how many papers need
to be checked

Write pseudocode for module CheckAll().

CheckMark() must be used to check each individual mark.

(c) The requirement changes. Instead of a new file, the module described in part (b) needs to add the corresponding candidate ID for each paper that needs to be checked to an existing file. 1 mark

Explain the change that will need to be made to CheckAll().

An exam paper has a maximum of 75 marks. One of five pass grades (A to E) is assigned, depending on the mark obtained. The lowest mark for a given grade is known as the grade boundary. For example, if the grade boundary for an A grade is 65 marks, then any candidate who achieves a mark of 65 or above will be awarded an A. A grade of U is awarded for marks below the E grade boundary. The five grade boundaries are stored in a global 1D array GradeBoundary of type integer. For example: |Element|Value|Comment| |---|---|---| |GradeBoundary[1]|65|The minimum mark for an A grade.| |GradeBoundary[2]|57|The minimum mark for a B grade.| |GradeBoundary[3]|43|The minimum mark for a C grade.| |GradeBoundary[4]|35|The minimum mark for a D grade.| |GradeBoundary[5]|27|The minimum mark for an E grade.| A global 2D array Result of type integer contains candidate marks for the exam. Each row relates to one candidate. Column 1 contains the candidate mark and column 2 contains the unique candidate ID. For example, for the fourth and fifth candidates: |Element|Mark| |---|---| |Result[4, 1]|56| |Result[5, 1]|54| |Element|ID| |---|---| |Result[4, 2]|1074832| |Result[5, 2]|2573839| There are more rows in the array than candidates who sit the exam. Any unused rows will be at the end of the array. Candidate papers that are given a mark within two marks of any grade boundary must be checked. For example, given the values in the example grade boundaries above, any paper that was awarded between 41 and 45 marks (inclusive) would need to be checked. A program is being written to identify papers that need to be checked. The programmer has defined the first program module as follows: |Module|Description| |---|---| |CheckMark()|• <br>called with a parameter of type integer representing a<br>candidate mark<br>• <br>returns TRUE if the mark is within 2 of any of the five grade<br>boundaries, otherwise returns FALSE| ### (a) Write pseudocode for module CheckMark(). <span class="part-marks">6 marks</span> ### (b) A second module is defined: <span class="part-marks">8 marks</span> |Module|Description| |---|---| |CheckAll()|• <br>called with a parameter of type integer representing the<br>number of candidate marks in the Result array<br>• <br>uses CheckMark() to check each candidate mark<br>• <br>for each paper that needs to be checked, write the<br>corresponding candidate ID on a separate line in a new file<br>named GRList.txt<br>• <br>outputs a message with a count of how many papers need<br>to be checked| Write pseudocode for module CheckAll(). CheckMark() must be used to check each individual mark. ### (c) The requirement changes. Instead of a new file, the module described in part (b) needs to add the corresponding candidate ID for each paper that needs to be checked to an existing file. <span class="part-marks">1 mark</span> Explain the change that will need to be made to CheckAll().
Show mark scheme

8(a) [6 marks]

Loop example solution FUNCTION CheckMark(Mark : INTEGER) RETURNS BOOLEAN DECLARE Index, Lower, Upper : INTEGER  FOR Index 1 TO 5  Lower GradeBoundary[Index] - 2  Upper GradeBoundary[Index] + 2 IF Mark >= Lower AND Mark <= Upper THEN RETURN TRUE ENDIF NEXT Index RETURN FALSE ENDFUNCTION Mark as follows: 1 Loop through all elements in array GradeBoundary 2 Attempt to calculate range, both and , in a loop Lower Upper 3 Completely correct range calculation in a loop 4 Test if given mark / parameter, is within range in a loop 5 Set variable / immediate RETURN if recheck required in a loop 6 Return Boolean in both cases following a reasonable attempt Selection example solution FUNCTION CheckMark(Mark : INTEGER) RETURNS BOOLEAN CASE OF Mark GradeBoundary[1] – 2 TO GradeBoundary[1] + 2 : RETURN TRUE GradeBoundary[2] – 2 TO GradeBoundary[2] + 2 : RETURN TRUE GradeBoundary[3] – 2 TO GradeBoundary[3] + 2 : RETURN TRUE GradeBoundary[4] – 2 TO GradeBoundary[4] + 2 : RETURN TRUE GradeBoundary[5] – 2 TO GradeBoundary[5] + 2 : RETURN TRUE OTHERWISE : RETURN FALSE ENDCASE ENDFUNCTION Mark as follows: 1 Correct syntax used for selection structure(s) 2 Correct checks for two ranges 3 Correct checks for three ranges 4 Correct checks for four ranges 5 Correct checks for all five ranges 6 Return Boolean in both cases following a reasonable attempt

8(b) [8 marks]

Example Solution: PROCEDURE CheckAll(CNum : INTEGER) DECLARE Index, Count, ThisMark: INTEGER  Count 0 OPENFILE "GRList.txt" FOR WRITE  FOR Index 1 to CNum  ThisMark Result[Index, 1] // 2D array: mark + ID IF CheckMark(ThisMark) = TRUE THEN WRITE "GRList.txt", NUM_TO_STR(Result[Index, 2])  Count Count + 1 ENDIF NEXT Index CLOSEFILE "GRList.txt" OUTPUT "There are ", Count, " papers to check" ENDPROCEDURE Mark as follows: 1 Procedure heading, parameter and ending. 2 Open file in write mode and subsequently close 3 Loop through all candidates CNum 4 Extract candidate mark from array in a loop Result 5 Use of with candidate mark as parameter in a loop CheckMark() 6 Test return value and if then increment in a loop TRUE Count 7 ... write ID to file ... 8 ... after conversion to a string in a loop 9 Final output of message giving number of papers to check not in a loop Max 8 marks

8(c) [1 mark]

The file will need to be opened in APPEND mode

Q6
Oct/Nov 2024 Paper 2 v2

A shop sells sandwiches and snacks. The owner chooses a ‘daily special’ sandwich which is displayed on a board outside the shop. Each ‘daily special’ has two different fillings and is made with one type of bread.

The owner wants a program to randomly choose the ‘daily special’ sandwich.

The program designer decides to store the possible sandwich fillings in a 1D array of type string.

The array is declared in pseudocode as follows:

DECLARE Filling : ARRAY [1:35] OF STRING

Each element contains the name of one filling.

An example of the first five elements is as follows:

Index Element value
1 "Cheese"
2 "Onion"
3 "Salmon"
4 "Anchovies"
5 "Peanut Butter"

A second 1D array stores the possible bread used:

DECLARE Bread : ARRAY [1:10] OF STRING

Each element contains the name of one type of bread.

An example of the first three elements is as follows:

Index Element value
1 "White"
2 "Brown"
3 "Pitta"

Both arrays may contain unused elements. The value of these will be an empty string and they may occur anywhere in each array.

A procedure Special() will output a message giving the ‘daily special’ sandwich made from two randomly selected different fillings and one randomly selected bread.

Unused array elements must not be used when creating the ‘daily special’ sandwich.

Using the above examples, the output could be:

"The daily special is Cheese and Onion on Brown bread."

(a) Complete the pseudocode for the procedure Special(). 7 marks

Assume that both arrays are global.

PROCEDURE Special()

ENDPROCEDURE

(b) The owner decides that some combinations of fillings do not go well together. For example, anchovies and peanut butter. 2 marks

Describe how the design could be changed to prevent certain combinations being selected.

A shop sells sandwiches and snacks. The owner chooses a ‘daily special’ sandwich which is displayed on a board outside the shop. Each ‘daily special’ has two different fillings and is made with one type of bread. The owner wants a program to randomly choose the ‘daily special’ sandwich. The program designer decides to store the possible sandwich fillings in a 1D array of type string. The array is declared in pseudocode as follows: DECLARE Filling : ARRAY [1:35] OF STRING Each element contains the name of one filling. An example of the first five elements is as follows: |Index|Element value| |---|---| |1|"Cheese"| |2|"Onion"| |3|"Salmon"| |4|"Anchovies"| |5|"Peanut Butter"| A second 1D array stores the possible bread used: DECLARE Bread : ARRAY [1:10] OF STRING Each element contains the name of one type of bread. An example of the first three elements is as follows: |Index|Element value| |---|---| |1|"White"| |2|"Brown"| |3|"Pitta"| Both arrays may contain unused elements. The value of these will be an empty string and they may occur anywhere in each array. A procedure Special() will output a message giving the ‘daily special’ sandwich made from two randomly selected different fillings and one randomly selected bread. Unused array elements must not be used when creating the ‘daily special’ sandwich. Using the above examples, the output could be: "The daily special is Cheese and Onion on Brown bread." ### (a) Complete the pseudocode for the procedure Special(). <span class="part-marks">7 marks</span> Assume that both arrays are global. PROCEDURE Special() ENDPROCEDURE ### (b) The owner decides that some combinations of fillings do not go well together. For example, anchovies and peanut butter. <span class="part-marks">2 marks</span> Describe how the design could be changed to prevent certain combinations being selected.
Show mark scheme

6(a) [7 marks]

Example solution: PROCEDURE Special() DECLARE Index : INTEGER DECLARE Filling1, Filling2 : STRING REPEAT  Index INT(RAND(35)) + 1 UNTIL Filling[Index] <> ""  Filling1 Filling[Index] REPEAT  Index INT(RAND(35)) + 1 UNTIL Filling[Index] <> AND Filling1 <> "" Filling[Index]  Filling2 Filling[Index] REPEAT  Index INT(RAND(10) + 1) UNTIL Bread[Index] <> "" OUTPUT The daily special is , Filling1, and , __ " " " " Filling2, on , Bread[Index], bread. " " " " ENDPROCEDURE Mark as follows: MP1 Loop for Filling 1, avoiding unused elements MP2 Loop for Filling 2 avoiding unused elements MP3 Check Filling 2 is different from Filling 1 – could correctly compare either the indices or the array contents MP4 Loop for Bread, avoiding unused elements MP5 Using / RAND(10) RAND(35) MP6 Completely correct use of including and +1 in all RAND()

INT() cases MP7 Correct output - once only – following a reasonable attempt at selection of filings and bread

6(b) [2 marks]

Answers include: MP1 For each filling, create a list of acceptable / incompatible fillings/indexes MP2 When selecting the second filling, (as well as checking for an unused element) check that the filling / index is / is not on the list ALTERNATIVE: MP1 Create a list of ‘good’ combinations MP2 Randomly select from this list •

Q8
Oct/Nov 2024 Paper 2 v2

A program is being developed to implement a game for up to six players.

During the game, each player assembles a team of characters. At the start of the game there are 45 characters available.

Each character has four attributes, as follows:

Attribute Examples Comment
Player 0, 1, 3 The player the character is assigned to.
Role Builder, Teacher, Doctor The job that the character will perform in the
game.
Name Bill, Lee, Farah, Mo The name of the character. Several characters
may perform the same role, but they will each
have a unique name.
Level 14, 23, 76 The skill level of the character. An integer in the
range 0 to 100 inclusive.

The programmer has defined a record type to define each character.

The record type definition is shown in pseudocode as follows:

TYPE CharacterType DECLARE Player : INTEGER DECLARE Role : STRING DECLARE Name : STRING DECLARE Level : INTEGER ENDTYPE

The Player field indicates the player to which the character is assigned (1 to 6). The field value is 0 if the character is not assigned to any player.

The programmer has defined a global array to store the character data as follows:

DECLARE Character : ARRAY[1:45] OF CharacterType

At the start of the game all record fields are initialised, and all Player field values are set to 0

The programmer has defined a program module as follows:

Module Description
Assign()
called with two parameters:


an integer representing a player


a string representing a character role

search the Character array for an unassigned character with the
required role

If found, assign the character to the given player and output a confirmation
message, for example:

"Bill the Builder has been assigned to player 3"

If no unassigned character with the required role is found, output a suitable
message.

(a) Write pseudocode for module Assign(). 7 marks

(b) A new module will store the contents of the Character array in a text file. 7 marks

The module is defined as follows:

Module Description
Save()
form a string from each record with fields separated by the
character '^'

write each string to a separate line of the new file named
SaveFile.txt

Complete the pseudocode for module Save().

PROCEDURE Save()

ENDPROCEDURE

(c) The program is changed and the record type definition is modified as follows: 2 marks

TYPE CharacterType DECLARE Player : INTEGER DECLARE Role : STRING DECLARE Name : STRING DECLARE Level : INTEGER DECLARE Status : BOOLEAN ENDTYPE

Describe how the additional Boolean field may be stored with the rest of the fields on one line of a text file.

(d) The save operation is to be extended so that multiple files may be saved as the game progresses. This will allow the user to restore the game from any saved position. The filename must reflect the sequence in which the files are saved. 2 marks

Describe a method that would allow multiple files to be saved and give an example of two consecutive filenames.

Method

Example

A program is being developed to implement a game for up to six players. During the game, each player assembles a team of characters. At the start of the game there are 45 characters available. Each character has four attributes, as follows: |Attribute|Examples|Comment| |---|---|---| |Player|0, 1, 3|The player the character is assigned to.| |Role|Builder, Teacher, Doctor|The job that the character will perform in the<br>game.| |Name|Bill, Lee, Farah, Mo|The name of the character. Several characters<br>may perform the same role, but they will each<br>have a unique name.| |Level|14, 23, 76|The skill level of the character. An integer in the<br>range 0 to 100 inclusive.| The programmer has defined a record type to define each character. The record type definition is shown in pseudocode as follows: TYPE CharacterType DECLARE Player : INTEGER DECLARE Role : STRING DECLARE Name : STRING DECLARE Level : INTEGER ENDTYPE The Player field indicates the player to which the character is assigned (1 to 6). The field value is 0 if the character is not assigned to any player. The programmer has defined a global array to store the character data as follows: DECLARE Character : ARRAY[1:45] OF CharacterType At the start of the game all record fields are initialised, and all Player field values are set to 0 The programmer has defined a program module as follows: |Module|Description| |---|---| |Assign()|• <br>called with two parameters:<br> <br>○<br>an integer representing a player<br> <br>○<br>a string representing a character role<br>• <br>search the Character array for an unassigned character with the<br>required role<br>• <br>If found, assign the character to the given player and output a confirmation<br>message, for example:<br> <br>"Bill the Builder has been assigned to player 3"<br>• <br>If no unassigned character with the required role is found, output a suitable<br>message.| ### (a) Write pseudocode for module Assign(). <span class="part-marks">7 marks</span> ### (b) A new module will store the contents of the Character array in a text file. <span class="part-marks">7 marks</span> The module is defined as follows: |Module|Description| |---|---| |Save()|• <br>form a string from each record with fields separated by the<br>character '^'<br>• <br>write each string to a separate line of the new file named<br>SaveFile.txt| Complete the pseudocode for module Save(). PROCEDURE Save() ENDPROCEDURE ### (c) The program is changed and the record type definition is modified as follows: <span class="part-marks">2 marks</span> TYPE CharacterType DECLARE Player : INTEGER DECLARE Role : STRING DECLARE Name : STRING DECLARE Level : INTEGER DECLARE Status : BOOLEAN ENDTYPE Describe how the additional Boolean field may be stored with the rest of the fields on one line of a text file. ### (d) The save operation is to be extended so that multiple files may be saved as the game progresses. This will allow the user to restore the game from any saved position. The filename must reflect the sequence in which the files are saved. <span class="part-marks">2 marks</span> Describe a method that would allow multiple files to be saved and give an example of two consecutive filenames. Method Example
Show mark scheme

8(a) [7 marks]

Example solution: PROCEDURE Assign(ThisRole : STRING, ThisPlayer : INTEGER) DECLARE Index : INTEGER DECLARE Done : BOOLEAN  Done FALSE  Index 1 WHILE Index < 46 AND Done = FALSE IF Character[Index].Player = 0 AND __ Character[Index].Role = ThisRole THEN  Character[Index].Player ThisPlayer  Done TRUE ELSE  Index Index + 1 ENDIF ENDWHILE IF Done = TRUE THEN OUTPUT Character[Index].Name, the ,__ " " Character[Index].Role, __ has been assigned to player , ThisPlayer " " ELSE OUTPUT No characters with this role are available " " ENDIF ENDPROCEDURE Mark as follows: MP1 Loop until ‘found’ or all 45 elements considered MP2 Test of field – i.e. not value in a loop Player MP3 ... – i.e. match for parameter in a loop AND Role ThisRole MP4 If available character found, assign to the character in a ThisPlayer loop MP5 When character found set termination condition/flag MP6 Both OUTPUT messages logically correctly placed MP7 Both OUTPUT statements correctly formed

8(b) [7 marks]

Example solution: PROCEDURE Save() DECLARE Index : INTEGER DECLARE Line : STRING CONSTANT SEP = '^' OPENFILE SaveFile.txt FOR WRITE " "  FOR Index 1 TO 45  Line NUM_TO_STR(Character[Index].Player) & SEP  Line Line & Character[Index].Role & SEP  Line Line & Character[Index].Name & SEP  Line Line & NUM_TO_STR(Character[Index].Level) WRITEFILE SaveFile.txt , Line " " NEXT Index CLOSEFILE SaveFile.txt " " ENDPROCEDURE Mark as follows: MP1 Declaration of local integer for ( and string type for Index Line) MP2 Open in write mode and subsequently close "SaveFile.txt" MP3 Loop through 45 elements MP4 Attempt to form

  • four fields in a loop Line MP5 Correct use of in a loop NUM_TO_STR()x2 (Player and Level) MP6 Correct use of three && in a loop strings MP7 Line from MP4 written to file in a loop

8(c) [2 marks]

MP1 Encode as a character / string Status MP2 Append the ‘^’ separator and the character/string

8(d) [2 marks]

MP1 Method: Create a filename suffix which is incremented for each file save MP2 Example: SaveFile01.txt, SaveFile02.txt

Q4
Oct/Nov 2024 Paper 2 v3

An examination paper has a maximum of 75 marks. One of five pass grades (A to E) is assigned, depending on the mark obtained. The lowest mark for a given grade is known as the grade boundary.

A program is being written to process examination marks.

The five grade boundaries are stored in a global 1D array GB of type INTEGER, for example:

Index Value Comment
1 65 The minimum mark for an A grade.
2 57 The minimum mark for a B grade.
3 43 The minimum mark for a C grade.
4 35 The minimum mark for a D grade.
5 27 The minimum mark for an E grade.

Any paper that achieves a mark within 2 marks of a grade boundary must be checked. Using the given table, a paper with 45 marks would need to be checked.

(a) The pseudocode algorithm to determine whether a paper should be checked is as shown. 4 marks

The mark for the paper is stored in variable Mark. Global variables Mark, Index, Upper and Lower are declared as integers.

Complete the pseudocode.

FOR Index ← 1 TO

Lower ← GB[Index] - 2

Upper ←

IF Mark ______ AND Mark ______ THEN

OUTPUT "Check this paper"

ENDIF

NEXT Index

(b) An alternative algorithm to determine if a paper needs to be checked uses a global 1D array Check, containing 76 elements of type BOOLEAN. The indices of the array are from 0 to 75 (inclusive), corresponding to the range of possible marks.

An element value in Check is TRUE if the index is within 2 marks of a grade boundary. For example, in the case where the C grade boundary is 43 the corresponding part of the Check array would be as follows:

← The grade boundary for a C grade

Index Value
40 FALSE
41 TRUE
42 TRUE
43 TRUE
44 TRUE
45 TRUE
46 FALSE

(i) The mark for a given paper is stored in variable Mark. 2 marks

Describe how an algorithm would use the Check array to determine whether this paper should be checked.

(ii) A procedure GBInitialise() will initialise the Check array using values from the GB array. 6 marks

Note it can be assumed that the maximum grade boundary value for A is 70 and the minimum value for E is 15.

Write pseudocode for the procedure.

An examination paper has a maximum of 75 marks. One of five pass grades (A to E) is assigned, depending on the mark obtained. The lowest mark for a given grade is known as the grade boundary. A program is being written to process examination marks. The five grade boundaries are stored in a global 1D array GB of type INTEGER, for example: |Index|Value|Comment| |---|---|---| |1|65|The minimum mark for an A grade.| |2|57|The minimum mark for a B grade.| |3|43|The minimum mark for a C grade.| |4|35|The minimum mark for a D grade.| |5|27|The minimum mark for an E grade.| Any paper that achieves a mark within 2 marks of a grade boundary must be checked. Using the given table, a paper with 45 marks would need to be checked. ### (a) The pseudocode algorithm to determine whether a paper should be checked is as shown. <span class="part-marks">4 marks</span> The mark for the paper is stored in variable Mark. Global variables Mark, Index, Upper and Lower are declared as integers. Complete the pseudocode. FOR Index ← 1 TO Lower ← GB[Index] - 2 Upper ← IF Mark ______ AND Mark ______ THEN OUTPUT "Check this paper" ENDIF NEXT Index ### (b) An alternative algorithm to determine if a paper needs to be checked uses a global 1D array Check, containing 76 elements of type BOOLEAN. The indices of the array are from 0 to 75 (inclusive), corresponding to the range of possible marks. An element value in Check is TRUE if the index is within 2 marks of a grade boundary. For example, in the case where the C grade boundary is 43 the corresponding part of the Check array would be as follows: # ← The grade boundary for a C grade |Index|Value| |---|---| |40|FALSE| |41|TRUE| |42|TRUE| |43|TRUE| |44|TRUE| |45|TRUE| |46|FALSE| #### (i) The mark for a given paper is stored in variable Mark. <span class="part-marks">2 marks</span> Describe how an algorithm would use the Check array to determine whether this paper should be checked. #### (ii) A procedure GBInitialise() will initialise the Check array using values from the GB array. <span class="part-marks">6 marks</span> Note it can be assumed that the maximum grade boundary value for A is 70 and the minimum value for E is 15. Write pseudocode for the procedure.
Show mark scheme

4(a) [4 marks]

One mark per highlighted part:  FOR Index 1 TO 5  Lower GB[Index] - 2  Upper GB[Index] + 2 // Lower + 4 IF Mark

= Lower AND Mark <= Upper THEN // IF Mark <= Upper AND Mark = Lower THEN OUTPUT "Check this paper" ENDIF NEXT Index

4(b)(i) [2 marks]

MP1 Use as the index to the array // to specify an array Mark Check element MP2 If value of indexed element is then the paper will need to be TRUE, checked

4(b)(ii)

ALTERNATIVE – Example using selection Version 2 DECLARE ThisIndex, GBIndex : INTEGER DECLARE Lower, Higher : INTEGER  FOR ThisIndex 0 TO 75  For GBIndex 1 T0 5  Lower GB[GBIndex] - 2  Higher GB[GBIndex] + 2 IF ThisIndex >= Lower AND ThisIndex <= Higher THEN  Check[ThisIndex] TRUE ELSE  Check[ThisIndex] FALSE ENDIF NEXT Index NEXT ThisIndex Mark as follows: MP1 Procedure heading and ending MP2 Loop through array// loop from 0 to 75 Check MP3 Attempt at using CASE / Selection structure with five clauses/ f ive checks for range MP4 Extract GB grade  MP5 Compare with each element in GB array 2 ThisIndex MP6 Assign each element of array to if in range or if Check TRUE FALSE not in range

Q8
Oct/Nov 2024 Paper 2 v3

A program is being developed to implement a game for up to six players.

During the game, each player assembles a team of characters. At the start of the game there are 45 characters available.

Each character has four attributes, as follows:

Attribute Examples Comment
Player 0, 1, 3 The player the character is assigned to.
Role Builder, Teacher, Doctor The job that the character will perform in the
game.
Name Bill, Lee, Farah, Mo The name of the character. Several characters
may perform the same role, but they will each
have a unique name.
Skill level 14, 23, 76 An integer in the range 0 to 100, inclusive.

The programmer has defined a record type to define each character. The record type definition is shown in pseudocode as follows:

TYPE CharacterType DECLARE Player : INTEGER DECLARE Role : STRING DECLARE Name : STRING DECLARE SkillLevel : INTEGER ENDTYPE

The Player field indicates the player to which the character is assigned (1 to 6). This field value is 0 if the character is not assigned to any player.

The programmer has defined a global array to store the character data, as follows:

DECLARE Character : ARRAY[1:45] OF CharacterType

At the start of the game all record fields are initialised, and all Player fields are set to 0

The programmer has defined a program module as follows:

Module Description
Count()
called with two parameters:


an integer representing a player


a string representing a character role

searches the Character array for characters with the given role that are
assigned to the given player

counts the number of assigned characters and sums their total skill level

outputs the result of the search if characters with the given role are found,
for example:

"Player 3 has 4 characters with the role of Teacher
and the total skill level is 65"

if no characters with the given role are found, outputs:

"No characters with that role are assigned to this
player"

(a) Complete the pseudocode for module Count(). 7 marks

PROCEDURE Count(ThisPlayer : INTEGER, ThisRole : STRING)

ENDPROCEDURE

(b) The Character array data has been saved in the text file SaveFile.txt Each line of the file contains one element of the array (one record). 7 marks

New modules are defined:

Module Description
Extract()
(already written)

called with two parameters:


a string representing a complete line from the text file


an integer representing a field number (see structure below)

returns a string representing the required field
Restore()
opens the text file SaveFile.txt

reads lines from the file and assigns values to each record in the
Character array using data from each line of the file

As a reminder, the record structure is repeated here:

TYPE CharacterType DECLARE Player : INTEGER //Field number 1 DECLARE Role : STRING //Field number 2 DECLARE Name : STRING //Field number 3 DECLARE SkillLevel : INTEGER //Field number 4 ENDTYPE

Write pseudocode for module Restore().

You must use the module Extract().

(c) The game can last for several days and users often find that they have to close and rerun the game program many times in order to complete it. 2 marks

Describe the benefit of using the file SaveFile.txt as described in part (b).

A program is being developed to implement a game for up to six players. During the game, each player assembles a team of characters. At the start of the game there are 45 characters available. Each character has four attributes, as follows: |Attribute|Examples|Comment| |---|---|---| |Player|0, 1, 3|The player the character is assigned to.| |Role|Builder, Teacher, Doctor|The job that the character will perform in the<br>game.| |Name|Bill, Lee, Farah, Mo|The name of the character. Several characters<br>may perform the same role, but they will each<br>have a unique name.| |Skill level|14, 23, 76|An integer in the range 0 to 100, inclusive.| The programmer has defined a record type to define each character. The record type definition is shown in pseudocode as follows: TYPE CharacterType DECLARE Player : INTEGER DECLARE Role : STRING DECLARE Name : STRING DECLARE SkillLevel : INTEGER ENDTYPE The Player field indicates the player to which the character is assigned (1 to 6). This field value is 0 if the character is not assigned to any player. The programmer has defined a global array to store the character data, as follows: DECLARE Character : ARRAY[1:45] OF CharacterType At the start of the game all record fields are initialised, and all Player fields are set to 0 The programmer has defined a program module as follows: |Module|Description| |---|---| |Count()|• <br>called with two parameters:<br> <br>○<br>an integer representing a player<br> <br>○<br>a string representing a character role<br>• <br>searches the Character array for characters with the given role that are<br>assigned to the given player<br>• <br>counts the number of assigned characters and sums their total skill level<br>• <br>outputs the result of the search if characters with the given role are found,<br>for example:<br> <br> "Player 3 has 4 characters with the role of Teacher<br>and the total skill level is 65"<br>• <br>if no characters with the given role are found, outputs:<br> <br> "No characters with that role are assigned to this<br>player"| ### (a) Complete the pseudocode for module Count(). <span class="part-marks">7 marks</span> PROCEDURE Count(ThisPlayer : INTEGER, ThisRole : STRING) ENDPROCEDURE ### (b) The Character array data has been saved in the text file SaveFile.txt Each line of the file contains one element of the array (one record). <span class="part-marks">7 marks</span> New modules are defined: |Module|Description| |---|---| |Extract()<br>(already written)|• <br>called with two parameters:<br> <br>○<br>a string representing a complete line from the text file<br> <br>○<br>an integer representing a field number (see structure below)<br>• <br>returns a string representing the required field| |Restore()|• <br>opens the text file SaveFile.txt<br>• <br>reads lines from the file and assigns values to each record in the<br>Character array using data from each line of the file| As a reminder, the record structure is repeated here: TYPE CharacterType DECLARE Player : INTEGER //Field number 1 DECLARE Role : STRING //Field number 2 DECLARE Name : STRING //Field number 3 DECLARE SkillLevel : INTEGER //Field number 4 ENDTYPE Write pseudocode for module Restore(). You must use the module Extract(). ### (c) The game can last for several days and users often find that they have to close and rerun the game program many times in order to complete it. <span class="part-marks">2 marks</span> Describe the benefit of using the file SaveFile.txt as described in part (b).
Show mark scheme

8(a) [7 marks]

Example solution PROCEDURE Count(ThisPlayer : INTEGER, ThisRole : STRING) DECLARE Index, Num, Total : INTEGER  Num 0  Total 0  FOR Index 1 TO 45 IF Character[Index].Player = ThisPlayer AND __ Character[Index].Role = ThisRole THEN  Num Num + 1  Total Total + Character[Index].SkillLevel NEXT Index IF Num > 0 THEN OUTPUT "Player ", ThisPlayer, __ " has ", Num, " characters with the role of ", ThisRole, " and the total skill level is ", Total ELSE OUTPUT "No characters with that role are assigned to this player" ENDIF ENDPROCEDURE MP1 Initialisation of local integers for and Num Total MP2 Loop through 45 elements MP3 Attempt to check Player and Role fields in a loop MP4 Correctly compare field with parameter in a loop Player MP5 Correctly compare field with parameter in a loop Role MP6 ... if player and role found, increment and sum Skill Total in a Num loop MP7 Test for any matches after the loop MP8 Both possible OUTPUT statements correctly formed following an attempt at MP6 but outputting one only Max 7 marks

8(b) [7 marks]

Example solution: PROCEDURE Restore() DECLARE Index : INTEGER DECLARE Line : STRING OPENFILE "SaveFile.txt" FOR READ  FOR Index 1 TO 45 READFILE "SaveFile.txt", Line  Character[Index].Player STR_TO_NUM(Extract(Line, 1))  Character[Index].Role Extract(Line, 2)  Character[Index].Name Extract(Line, 3)  Character[Index].Skill STR_TO_NUM(Extract(Line, 4)) NEXT Index CLOSEFILE "SaveFile.txt" ENDPROCEDURE Mark as follows: MP1 Open the file in read mode and subsequently close MP2 Loop through 45 elements MP3 Read a line from the file in a loop MP4 Attempt to use in a loop Extract() MP5 Correct use of for all fields in a loop Extract() MP6 Use of on Player and Skill in a loop STR_TO_NUM() MP7 Completely correct extraction and assignment of all fields in a loop

8(c) [2 marks]

MP1 The array / character data can be saved before the Character program is closed MP2 Allowing the game to continue using the same data / from the point it was saved

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

Q4
May/Jun 2024 Paper 2 v1

A global 1D array Data contains 100 elements of type integer.

A function Check() will:

  • total the element values in odd index locations (1, 3, 5 ... 97, 99)

  • total the element values in even index locations (2, 4, 6 ... 98, 100)

  • return one of three strings ‘Odd’, ‘Even’ or ‘Same’ to indicate which total is the greater, or whether the totals are the same.

Write pseudocode for the function Check() . 6 marks

A global 1D array `Data` contains 100 elements of type integer. A function `Check()` will: - total the element values in odd index locations (1, 3, 5 ... 97, 99) - total the element values in even index locations (2, 4, 6 ... 98, 100) - return one of three strings ‘Odd’, ‘Even’ or ‘Same’ to indicate which total is the greater, or whether the totals are the same. Write pseudocode for the function `Check()` . <span class="part-marks">6 marks</span>
Show mark scheme

4 Example:

FUNCTION Check() RETURNS STRING DECLARE Odd, Even, Index : INTEGER  Odd 0  Even 0  FOR Index 1 TO 100 IF Index MOD 2 = 0 THEN  Even Even + Data[Index] ELSE  Odd Odd + Data[Index] ENDIF NEXT Index ENDFUNCTION Mark as follows:

  1. Function heading, ending and return type
  2. Declare local variables and as integers Odd, Even Index
  3. Initialise and Odd Even
  4. Loop for 100 // through array iterations
  5. Sum and element values in a loop Odd Even
  6. Compare and after the loop and Return appropriate string Odd Even
Q5
May/Jun 2024 Paper 2 v1

A global 1D array of strings contains three elements which are assigned values as shown:

  Data[1]  "aaaaaa"
  Data[2]  "bbbbbb"
  Data[3]  "cccccc"

Procedure Process() manipulates the values in the array.

The procedure is written in pseudocode as follows:

  PROCEDURE Process(Format : STRING)
  DECLARE Count, Index, L : INTEGER
  DECLARE Result : STRING
  DECLARE C : CHAR
  Result  "****"
  FOR Count  1 TO LENGTH(Format) STEP 2
  C  MID(Format, Count, 1)
  L  STR_TO_NUM(MID(Format, Count + 1, 1))
  Index  (Count + 1) DIV 2
  CASE OF C
  'X' : Result  TO_UPPER(Data[Index])
  'Y' : Result  TO_LOWER(Data[Index])
  'Z' : Result  "**" & Data[Index]
  ENDCASE
  Data[Index]  LEFT(Result, L)
  NEXT Count
  ENDPROCEDURE

(a) Complete the trace table by dry running the procedure when it is called as follows: 6 marks

    CALL Process("X3Y2W4")

|Count|C|L|Index|Result|Data[1]|Data[2]|Data[3]|
|---|---|---|---|---|---|---|---|
|||||||||
|||||||||
|||||||||
|||||||||
|||||||||
|||||||||
|||||||||
|||||||||
|||||||||
|||||||||
|||||||||
|||||||||
|||||||||
|||||||||

(b) The procedure is to be modified. If variable C is assigned a value other than 'X', 'Y' or 'Z', then procedure Error() is called and passed the value of variable C as a parameter.

This modification can be implemented by adding a single line of pseudocode.

(i) Write the single line of pseudocode. 1 mark

(ii) State where this new line should be placed. 1 mark

A global 1D array of strings contains three elements which are assigned values as shown: ``` Data[1] "aaaaaa" Data[2] "bbbbbb" Data[3] "cccccc" ``` Procedure `Process()` manipulates the values in the array. The procedure is written in pseudocode as follows: ``` PROCEDURE Process(Format : STRING) DECLARE Count, Index, L : INTEGER DECLARE Result : STRING DECLARE C : CHAR Result "****" FOR Count 1 TO LENGTH(Format) STEP 2 C MID(Format, Count, 1) L STR_TO_NUM(MID(Format, Count + 1, 1)) Index (Count + 1) DIV 2 CASE OF C 'X' : Result TO_UPPER(Data[Index]) 'Y' : Result TO_LOWER(Data[Index]) 'Z' : Result "**" & Data[Index] ENDCASE Data[Index] LEFT(Result, L) NEXT Count ENDPROCEDURE ``` ### (a) Complete the trace table by dry running the procedure when it is called as follows: <span class="part-marks">6 marks</span> ``` CALL Process("X3Y2W4") |Count|C|L|Index|Result|Data[1]|Data[2]|Data[3]| |---|---|---|---|---|---|---|---| ||||||||| ||||||||| ||||||||| ||||||||| ||||||||| ||||||||| ||||||||| ||||||||| ||||||||| ||||||||| ||||||||| ||||||||| ||||||||| ||||||||| ``` ### (b) The procedure is to be modified. If variable `C` is assigned a value other than `'X'`, `'Y'` or `'Z'`, then procedure `Error()` is called and passed the value of variable `C` as a parameter. This modification can be implemented by adding a **single line** of pseudocode. #### (i) Write the single line of pseudocode. <span class="part-marks">1 mark</span> #### (ii) State where this new line should be placed. <span class="part-marks">1 mark</span>
Show mark scheme

5(a) [6 marks]

One mark per zone. OTHERWISE : CALL Error(C)

5(b)(ii) [6 marks]

After the ' ' clause in the construct // before the Z CASE ENDCASE FUNCTION IsRA(x1, y1, x2, y2, x3, y3 : INTEGER) RETURNS

Q3
May/Jun 2024 Paper 2 v2

A factory needs a program to help manage its production of items.

Data will be stored about each item.

The data for each item will be held in a record structure of type Component .

The programmer has started to define the fields that will be needed as shown in the table.

Field Example value Comment
Item_Num 123478 a numeric value used as an array index
Reject FALSE TRUE if this item has been rejected
Stage 'B' a letter to indicate the stage of production
Limit_1 13.5 any value in the range 0 to 100 inclusive
Limit_2 26.4 any value in the range 0 to 100 inclusive

(a) (i) Write pseudocode to declare the record structure for type Component . 4 marks

(ii) A 1D array Item of 2000 elements will store the data for all items. 2 marks

Write pseudocode to declare the Item array.

(b) State three benefits of using an array of records to store the data for all items. 3 marks

1

2

3

A factory needs a program to help manage its production of items. Data will be stored about each item. The data for each item will be held in a record structure of type `Component` . The programmer has started to define the fields that will be needed as shown in the table. |Field|Example value|Comment| |---|---|---| |`Item_Num`|`123478`|a numeric value used as an array index| |`Reject`|`FALSE`|`TRUE` if this item has been rejected| |`Stage`|`'B'`|a letter to indicate the stage of production| |`Limit_1`|`13.5`|any value in the range 0 to 100 inclusive| |`Limit_2`|`26.4`|any value in the range 0 to 100 inclusive| **(a) (i)** Write pseudocode to declare the record structure for type `Component` . <span class="part-marks">4 marks</span> #### (ii) A 1D array `Item` of 2000 elements will store the data for all items. <span class="part-marks">2 marks</span> Write pseudocode to declare the `Item` array. ### (b) State **three** benefits of using an array of records to store the data for all items. <span class="part-marks">3 marks</span> 1 2 3
Show mark scheme

3(a)(i) [2 marks]

Pseudocode: TYPE Component DECLARE Item_Num : INTEGER DECLARE Reject : BOOLEAN DECLARE Stage : CHAR DECLARE Limit_1 : REAL DECLARE Limit_2 : REAL ENDTYPE Mark as follows: 1 One mark for and statements TYPE ENDTYPE 2 One mark for and fields Item_Num Reject 3 One mark for field Stage 4 One mark for Limit fields as REAL DECLARE Item : ARRAY [1:2000] OF Component//

3(a)(ii) [3 marks]

DECLARE Item : ARRAY [2000] OF Component// DECLARE Item : ARRAY [0:1999] OF Component One mark per underlined phrase

3(b) [5 marks]

One mark per point: 1 Allows for iteration / can use a loop to access the records / data items 2 Use of index to directly access a record in the array // Example of simplification of code e.g. use of dot notation Item[1].Stage 3 Simplifies the code / algorithm // Reduces duplication of code // Program easier to write / understand / maintain / test / debug // Data items/record easier to search / sort / manipulate

Q5
May/Jun 2024 Paper 2 v2

A program is being designed in pseudocode.

The program contains a global 1D array Data of type string containing 200 elements.

The first element has the index value 1.

A procedure Process() is written to initialise the values in the array:

  PROCEDURE Process(Label : STRING)
  DECLARE Index : INTEGER
  Index  0
  INPUT Data[Index]
  WHILE Index < 200
  Index  Index + 1
  CASE OF (Index MOD 2)
  0 : Data[Index]  TO_UPPER(Label)
  1 : Data[Index]  TO_LOWER(Label)
  OTHERWISE : OUTPUT "Alarm 1201"
  ENDCASE
  NEXT Index
  OUTPUT "Completed " & Index & " times"
  ENDPROCEDURE

(a) (i) The pseudocode contains two syntax errors and one other error. 3 marks

Identify the errors.

Syntax error 1

Syntax error 2

Other error

(ii) The procedure contains a statement that is not needed. 2 marks

Identify the pseudocode statement and explain why it is not needed.

Statement

Explanation

(b) After correcting all syntax errors, the pseudocode is translated into program code which compiles without generating any errors. 1 mark

When the program is executed it unexpectedly stops responding.

Identify the type of error that has occurred.

A program is being designed in pseudocode. The program contains a global 1D array `Data` of type string containing 200 elements. The first element has the index value 1. A procedure `Process()` is written to initialise the values in the array: ``` PROCEDURE Process(Label : STRING) DECLARE Index : INTEGER Index 0 INPUT Data[Index] WHILE Index < 200 Index Index + 1 CASE OF (Index MOD 2) 0 : Data[Index] TO_UPPER(Label) 1 : Data[Index] TO_LOWER(Label) OTHERWISE : OUTPUT "Alarm 1201" ENDCASE NEXT Index OUTPUT "Completed " & Index & " times" ENDPROCEDURE ``` **(a) (i)** The pseudocode contains **two** syntax errors and **one** other error. <span class="part-marks">3 marks</span> Identify the errors. Syntax error 1 Syntax error 2 Other error #### (ii) The procedure contains a statement that is **not** needed. <span class="part-marks">2 marks</span> Identify the pseudocode statement **and** explain why it is **not** needed. Statement Explanation ### (b) After correcting all syntax errors, the pseudocode is translated into program code which compiles without generating any errors. <span class="part-marks">1 mark</span> When the program is executed it unexpectedly stops responding. Identify the type of error that has occurred.
Show mark scheme

5(a)(i) [2 marks]

One mark per error: Syntax: 1. (should be NEXT Index ENDWHILE) 2. '&' used to concatenate an integer (in statement) OUTPUT Other: 3. Accesses element outside range // Accesses element 0

5(a)(ii)

One mark per point: Statement:  The statement OTHERWISE Explanation:  The result of MOD 2 can only be 0 or 1

5(b) [7 marks]

Run-time

Q2
May/Jun 2024 Paper 2 v3

(a) A program uses a global 1D array of type string and a text file. 5 marks

An algorithm that forms part of the program is expressed as follows:

  • copy the first line from the file into the first element of the array

  • copy the second line from the file into the second element of the array

  • continue until all lines in the file have been copied into the array.

Stepwise refinement is applied to the algorithm.

Outline five steps for this algorithm that could be used to produce pseudocode.

Assume there are more elements in the array than lines in the file.

Do not use pseudocode statements in your answer.

Step 1

Step 2

Step 3

Step 4

Step 5

(b) Sequence is one programming construct. 2 marks

Identify one other programming construct that will be required when the algorithm from part (a) is converted into pseudocode and explain its use.

Construct

Use

### (a) A program uses a global 1D array of type string and a text file. <span class="part-marks">5 marks</span> An algorithm that forms part of the program is expressed as follows: - copy the first line from the file into the first element of the array - copy the second line from the file into the second element of the array - continue until all lines in the file have been copied into the array. Stepwise refinement is applied to the algorithm. Outline **five** steps for this algorithm that could be used to produce pseudocode. Assume there are more elements in the array than lines in the file. Do **not** use pseudocode statements in your answer. Step 1 Step 2 Step 3 Step 4 Step 5 ### (b) Sequence is one programming construct. <span class="part-marks">2 marks</span> Identify **one other** programming construct that will be required when the algorithm from part **(a)** is converted into pseudocode **and** explain its use. Construct Use
Show mark scheme

2(a)

One mark per point:

  1. Open the file (in read mode and subsequently close)
  2. Initialise an index variable (to 1 // 0)
  3. Repeat (the next three steps) until the end of file is reached
  4. Read a line from the file (into a string variable)
  5. Store the line / variable in the array at the index
  6. Increment the index in a loop Note: max 5 marks

2(b) [3 marks]

One mark per point: Construct: a conditional loop Use: To keep repeating until the end of the file is reached ALTERNATIVE: Construct: a selection statement Use: To test / check the value returned by the function EOF()

Q3
May/Jun 2024 Paper 2 v3

A record structure is declared to hold data relating to components being produced in a factory:

TYPE Component DECLARE Item_ID : STRING DECLARE Reject : BOOLEAN DECLARE Weight : REAL ENDTYPE

The factory normally produces a batch (or set) of 1000 components at a time. A global array is declared to store 1000 records for a batch:

DECLARE Batch : ARRAY [1:1000] OF Component

Two global variables contain the minimum and maximum acceptable weight for each component. The values represent an inclusive range and are declared as:

DECLARE Min, Max : REAL

(a) (i) A program uses a variable ThisIndex as the array index to access a record. 3 marks

Write a pseudocode clause to check whether or not the weight of an individual component is within the acceptable range.

(ii) When batches of less than 1000 components are processed, it is necessary to indicate that certain elements in the array are unused. 1 mark

Suggest how an unused array element could be indicated.

(b) A module InRange() will:

  • be called with an integer parameter representing an index value of a record in the Batch array

  • check if the weight of the indexed component is within the acceptable range

  • return TRUE if the weight is in the range and FALSE if it is not .

A module BatchCheck() will:

  • iterate through a batch of 1000 component records

  • call module InRange() to check each individual component record

  • keep a count of the number of components that fail

  • output a suitable warning message and immediately stop if the number of failed components exceeds 5.

A record structure is declared to hold data relating to components being produced in a factory: TYPE Component DECLARE Item_ID : STRING DECLARE Reject : BOOLEAN DECLARE Weight : REAL ENDTYPE The factory normally produces a batch (or set) of 1000 components at a time. A global array is declared to store 1000 records for a batch: DECLARE Batch : ARRAY [1:1000] OF Component Two global variables contain the minimum and maximum acceptable weight for each component. The values represent an inclusive range and are declared as: DECLARE Min, Max : REAL **(a) (i)** A program uses a variable ThisIndex as the array index to access a record. <span class="part-marks">3 marks</span> Write a pseudocode clause to check whether or **not** the weight of an individual component is within the acceptable range. #### (ii) When batches of less than 1000 components are processed, it is necessary to indicate that certain elements in the array are unused. <span class="part-marks">1 mark</span> Suggest how an unused array element could be indicated. ### (b) A module InRange() will: - be called with an integer parameter representing an index value of a record in the Batch array - check if the weight of the indexed component is within the acceptable range - return TRUE if the weight is in the range and FALSE if it is **not** . A module BatchCheck() will: - iterate through a batch of 1000 component records - call module InRange() to check each individual component record - keep a count of the number of components that fail - output a suitable warning message and immediately stop if the number of failed components exceeds 5.
Show mark scheme

3(a)(i)

Example solution using AND IF Batch[ThisIndex].Weight >= Min AND Batch[ThisIndex].Weight <= Max THEN Alternative solution using OR IF Batch[ThisIndex].Weight < Min OR Batch[ThisIndex].Weight > Max THEN Mark as follows:

  1. Reference to Batch[ThisIndex].Weight
  2. A valid check for one boundary
  3. A valid check for other boundary with correct logic operator

3(a)(ii) [5 marks]

One mark for either:  Set the field to an empty string / NULL / invalid value Item_ID  Set to <= 0 / zero Weight

3(b) [6 marks]

ne 1 Zo ne 2 Zo ne 3 Zo ne 4 Zo ne 5 Zo One mark per zone

Q4
May/Jun 2024 Paper 2 v3

A procedure TwoParts() will input a sequence of real values, one at a time.

The procedure will:

  • process the sequence in two parts

  • form a first total by adding the values until the first zero

  • form a second total by adding the values after the first zero until the second zero

  • output the average of the two totals, together with a suitable message.

Values input in the first part are totalled using global variable TotalA and those input in the second part are totalled using global variable TotalB.

(a) Write pseudocode for the procedure TwoParts(). 6 marks

(b) The value zero denotes the split between the two parts of the sequence.

The requirement changes and now there may be up to 20 parts.

(i) Identify a suitable data structure that could be used to store the different total values. 2 marks

(ii) Describe three benefits of using the data structure given in part (b)(i) . 3 marks

1

2

3

A procedure TwoParts() will input a sequence of real values, one at a time. The procedure will: - process the sequence in two parts - form a first total by adding the values until the first zero - form a second total by adding the values after the first zero until the second zero - output the average of the two totals, together with a suitable message. Values input in the first part are totalled using global variable TotalA and those input in the second part are totalled using global variable TotalB. ### (a) Write pseudocode for the procedure TwoParts(). <span class="part-marks">6 marks</span> ### (b) The value zero denotes the split between the two parts of the sequence. The requirement changes and now there may be up to 20 parts. #### (i) Identify a suitable data structure that could be used to store the different total values. <span class="part-marks">2 marks</span> #### (ii) Describe **three** benefits of using the data structure given in part **(b)(i)** . <span class="part-marks">3 marks</span> 1 2 3
Show mark scheme

4(a) [2 marks]

Example solution: PROCEDURE TwoParts() DECLARE NextNum, Average : REAL  TotalA 0.0 // 0  TotalB 0.0 // 0 REPEAT INPUT NextNum  TotalA TotalA + NextNum UNTIL NextNum = 0 REPEAT INPUT NextNum  TotalB TotalB + NextNum UNTIL NextNum = 0  Average (TotalA + TotalB) / 2 OUTPUT "The average is ", Average ENDPROCEDURE Mark as follows:

  1. Procedure heading and ending
  2. Declare all local variables
  3. Initialise and TotalA TotalB
  4. First conditional loop until zero entered, summing // Loop until TotalA both parts (sequences) have been entered
  5. Second conditional loop until zero entered, summing // Loop TotalB summing appropriate Totals
  6. Calculation of average and output with a message // Calculation of the average for the values making up the two totals and both output with a suitable message

4(b)(i) [3 marks]

(1D) array of 20 reals Marks as follows: 1 mark for array 1 mark for 20 reals

4(b)(ii)

One mark per point: 1 (Multiple instances referenced via a single identifier so) fewer identifiers needed 2 Easier to process / search / organise / access the data // Values may be accessed via a loop-controlled variable /an index //An array / data can be iterated through 3 Makes the program/algorithm easier to write / design / understand / maintain / modify // Simplifies the program // Easier to debug / test

Q5
May/Jun 2024 Paper 2 v3

A program is being designed in pseudocode.

The program contains the following declaration:

DECLARE Data : ARRAY[1:1000] OF STRING

A procedure ArrayInitialise() is written to initialise the values in the array:

PROCEDURE ArrayInitialise(Label : STRING) DECLARE Index : INTEGER Index 1 WHILE Index <= 1000 CASE OF (Index MOD 2) 0 : Data[Index] FormatA(Label) Index Index + 1 1 : Data[Index] FormatB(Label) Index Index + 1 ENDCASE ENDWHILE ENDPROCEDURE

Functions FormatA() and FormatB() apply fixed format case changes to the parameter string.

(a) The design of the procedure does not use the most appropriate loop construct. 2 marks

Suggest a more appropriate construct that could be used and explain your choice.

Construct

Explanation

(b) The algorithm calls one of the functions FormatA() and FormatB() each time within the loop. 4 marks

Explain why this is not efficient and suggest a more efficient solution.

A program is being designed in pseudocode. The program contains the following declaration: DECLARE Data : ARRAY[1:1000] OF STRING A procedure ArrayInitialise() is written to initialise the values in the array: PROCEDURE ArrayInitialise(Label : STRING) DECLARE Index : INTEGER Index 1 WHILE Index <= 1000 CASE OF (Index MOD 2) 0 : Data[Index] FormatA(Label) Index Index + 1 1 : Data[Index] FormatB(Label) Index Index + 1 ENDCASE ENDWHILE ENDPROCEDURE Functions FormatA() and FormatB() apply fixed format case changes to the parameter string. ### (a) The design of the procedure does **not** use the most appropriate loop construct. <span class="part-marks">2 marks</span> Suggest a **more appropriate** construct that could be used **and** explain your choice. Construct Explanation ### (b) The algorithm calls one of the functions FormatA() and FormatB() each time within the loop. <span class="part-marks">4 marks</span> Explain why this is **not** efficient **and** suggest a more efficient solution.
Show mark scheme

5(a) [4 marks]

One mark per point  Count-controlled loop  the number of iterations is known

5(b) [6 marks]

Two mark for Statement of Problem: 1 The functions will return the same value every time they are called 2 ... because / the parameter value does not change within the loop Label Two marks for Solution: 3 Assign and to two (local) variables FormatA(Label) FormatB(Label) before the loop 4 Use the (new) variables in place of the function calls / in the loop // Replace the references to and in the FormatA() FormatB() CASE clauses with the new variable names

Q1
May/Jun 2024 Paper 4 v1

A program needs to take integer numbers as input, sort the numbers and then search for a specific number.

(a) The integer numbers will be stored in the global 1D array, DataStored, with space for up to 20 integers. 1 mark

The global variable NumberItems stores the quantity of items the array contains.

Write program code to declare DataStored and NumberItems .

Save your program as Question1_J24 .

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

(b) The procedure Initialise() : 5 marks

  • prompts the user to input the quantity of numbers the user would like to enter

  • reads the input and validates it is between 1 and 20 (inclusive)

  • prompts the user to input each number and stores each number in DataStored .

Write program code for Initialise() .

Save your program.

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

A program needs to take integer numbers as input, sort the numbers and then search for a specific number. ### (a) The integer numbers will be stored in the global 1D array, `DataStored`, with space for up to 20 integers. <span class="part-marks">1 mark</span> The global variable `NumberItems` stores the quantity of items the array contains. Write program code to declare `DataStored` and `NumberItems` . Save your program as **Question1_J24** . Copy and paste the program code into part **1(a)** in the evidence document. ### (b) The procedure `Initialise()` : <span class="part-marks">5 marks</span> - prompts the user to input the quantity of numbers the user would like to enter - reads the input and validates it is between 1 and 20 (inclusive) - prompts the user to input each number and stores each number in `DataStored` . Write program code for `Initialise()` . Save your program. Copy and paste the program code into part **1(b)** in the evidence document.
Show mark scheme

1(a) [1 mark]

1 mark for: Declaration of (global) array with identifier DataStored (Integer and 20 spaces) and NumberItems (Integer) public static Integer[] DataStored = new Integer[20]; public static Integer NumberItems= 0; VB.NET Dim DataStored(19) As Integer Dim NumberStored As Integer = 0 Python global DataStored #integer global NumberItems #Integer 20 items

1(b)

Python def Initialise(): global DataStored global NumberItems Valid = False while(Valid == False): NumberItems = int(input("How many numbers will you enter?")) #loop until < 20 if NumberItems > 0 and NumberItems< 21: Valid = True for Count in range(0, NumberItems): DataStored.append(int(input("Enter number")))

1(c)(i) [2 marks]

1 mark each: Storing 0 in NumberItems and then calling Initialise() Outputting all contents of array DataStored public static Integer NumberItems= 0; Initialise(); for(Integer X = 0; X < NumberItems; X++){ System.out.println(DataStored[X]); VB.NET NumberItems = 0 Initialise() For X = 0 To NumberItems - 1 Console.WriteLine(DataStored(X)) Python NumberItems = 0 Initialise() print(DataStored)

1(c)(ii) [2 marks]

1 mark each Output showing quantity entered twice (30 and 5) with first being invalid Array output 3 9 4 1 2

1(d)(i)

Python def BubbleSort(): global DataStored global NumberItems for Count in range(0, NumberItems): for Count2 in range(0, NumberItems-1): if DataStored[Count2] > DataStored[Count]: DataStored[Count2], DataStored[Count] = DataStored[Count], DataStored[Count2]

1(d)(ii) [1 mark]

1 mark for calling BubbleSort() and outputting array contents after VB.NET BubbleSort() For X = 0 To NumberStored - 1 Console.WriteLine(DataStored(X)) e.g. Java BubbleSort(); for(Integer X = 0; X < NumberItems; X++){ System.out.println(DataStored[X]); e.g. Python BubbleSort() print(DataStored)

1(d)(iii) [1 mark]

1 mark for screenshot showing the inputs and the values in the correct order

1(e)(i)

VB.NET Function BinarySearch(DataToFind) Dim First As Integer = 0 Dim Last As Integer = NumberItems Dim MidValue As Integer While (First <= Last) MidValue = (First + Last) / 2 If DataToFind = DataStored(MidValue) Then Return MidValue End If If DataToFind < DataStored(MidValue) Then Last = MidValue - 1 Else First = MidValue + 1 End If End While Return -1 End Function Python def BinarySearch(DataToFind): global DataStored global NumberItems First = 0 Last= NumberItems while(First <= Last): MidValue = int((First + Last) / 2) if DataToFind == DataStored[MidValue]: return MidValue if DataToFind < DataStored[MidValue]: Last = MidValue - 1 else: First = MidValue + 1 return -1

1(e)(ii) [3 marks]

1 mark each: Taking number as input … calling BinarySearch with input Outputting value returned Scanner scanner = new Scanner(System.in); System.out.println("Enter a number to find"); Integer Search = Integer.parseInt(scanner.nextLine()); System.out.println(BinarySearch(Search)); VB.NET Console.WriteLine("Enter a number to find") Dim Search As Integer = Console.ReadLine() Console.WriteLine(BinarySearch(Search)) Python Search = int(input("Enter a number to find")) print(BinarySearch(Search))

1(e)(iii) [2 marks]

1 mark for each test Test 1 – Accept found in index 16

Q1
May/Jun 2024 Paper 4 v3

A program needs to take integer numbers as input, sort the numbers and then search for a specific number.

(a) The integer numbers will be stored in the global 1D array, DataStored, with space for up to 20 integers. 1 mark

The global variable NumberItems stores the quantity of items the array contains.

Write program code to declare DataStored and NumberItems .

Save your program as Question1_J24 .

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

(b) The procedure Initialise() : 5 marks

  • prompts the user to input the quantity of numbers the user would like to enter

  • reads the input and validates it is between 1 and 20 (inclusive)

  • prompts the user to input each number and stores each number in DataStored .

Write program code for Initialise() .

Save your program.

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

A program needs to take integer numbers as input, sort the numbers and then search for a specific number. ### (a) The integer numbers will be stored in the global 1D array, `DataStored`, with space for up to 20 integers. <span class="part-marks">1 mark</span> The global variable `NumberItems` stores the quantity of items the array contains. Write program code to declare `DataStored` and `NumberItems` . Save your program as **Question1_J24** . Copy and paste the program code into part **1(a)** in the evidence document. ### (b) The procedure `Initialise()` : <span class="part-marks">5 marks</span> - prompts the user to input the quantity of numbers the user would like to enter - reads the input and validates it is between 1 and 20 (inclusive) - prompts the user to input each number and stores each number in `DataStored` . Write program code for `Initialise()` . Save your program. Copy and paste the program code into part **1(b)** in the evidence document.
Show mark scheme

1(a) [1 mark]

1 mark for: Declaration of (global) array with identifier DataStored (Integer and 20 spaces) and NumberItems (Integer) public static Integer[] DataStored = new Integer[20]; public static Integer NumberItems= 0; VB.NET Dim DataStored(19) As Integer Dim NumberStored As Integer = 0 Python global DataStored #integer global NumberItems #Integer 20 items

1(b)

Python def Initialise(): global DataStored global NumberItems Valid = False while(Valid == False): NumberItems = int(input("How many numbers will you enter?")) #loop until < 20 if NumberItems > 0 and NumberItems< 21: Valid = True for Count in range(0, NumberItems): DataStored.append(int(input("Enter number")))

1(c)(i) [2 marks]

1 mark each: Storing 0 in NumberItems and then calling Initialise() Outputting all contents of array DataStored public static Integer NumberItems= 0; Initialise(); for(Integer X = 0; X < NumberItems; X++){ System.out.println(DataStored[X]); VB.NET NumberItems = 0 Initialise() For X = 0 To NumberItems - 1 Console.WriteLine(DataStored(X)) Python NumberItems = 0 Initialise() print(DataStored)

1(c)(ii) [2 marks]

1 mark each Output showing quantity entered twice (30 and 5) with first being invalid Array output 3 9 4 1 2

1(d)(i)

Python def BubbleSort(): global DataStored global NumberItems for Count in range(0, NumberItems): for Count2 in range(0, NumberItems-1): if DataStored[Count2] > DataStored[Count]: DataStored[Count2], DataStored[Count] = DataStored[Count], DataStored[Count2]

1(d)(ii) [1 mark]

1 mark for calling BubbleSort() and outputting array contents after VB.NET BubbleSort() For X = 0 To NumberStored - 1 Console.WriteLine(DataStored(X)) e.g. Java BubbleSort(); for(Integer X = 0; X < NumberItems; X++){ System.out.println(DataStored[X]); e.g. Python BubbleSort() print(DataStored)

1(d)(iii) [1 mark]

1 mark for screenshot showing the inputs and the values in the correct order

1(e)(i)

VB.NET Function BinarySearch(DataToFind) Dim First As Integer = 0 Dim Last As Integer = NumberItems Dim MidValue As Integer While (First <= Last) MidValue = (First + Last) / 2 If DataToFind = DataStored(MidValue) Then Return MidValue End If If DataToFind < DataStored(MidValue) Then Last = MidValue - 1 Else First = MidValue + 1 End If End While Return -1 End Function Python def BinarySearch(DataToFind): global DataStored global NumberItems First = 0 Last= NumberItems while(First <= Last): MidValue = int((First + Last) / 2) if DataToFind == DataStored[MidValue]: return MidValue if DataToFind < DataStored[MidValue]: Last = MidValue - 1 else: First = MidValue + 1 return -1

1(e)(ii) [3 marks]

1 mark each: Taking number as input … calling BinarySearch with input Outputting value returned Scanner scanner = new Scanner(System.in); System.out.println("Enter a number to find"); Integer Search = Integer.parseInt(scanner.nextLine()); System.out.println(BinarySearch(Search)); VB.NET Console.WriteLine("Enter a number to find") Dim Search As Integer = Console.ReadLine() Console.WriteLine(BinarySearch(Search)) Python Search = int(input("Enter a number to find")) print(BinarySearch(Search))

1(e)(iii) [2 marks]

1 mark for each test Test 1 – Accept found in index 16

Q4
Oct/Nov 2023 Paper 2 v1

A global array is declared in pseudocode as follows:

    DECLARE Data : ARRAY[1:150] OF STRING

A function TooMany() will:

  1. take two parameters:
  • a string (the search string)

  • an integer (the maximum value)

  1. count the number of strings in the array that exactly match the search string
  2. return TRUE if the count is greater than the maximum value, otherwise will return FALSE

(a) Write pseudocode for the function TooMany(). 6 marks

A global array is declared in pseudocode as follows: ``` DECLARE Data : ARRAY[1:150] OF STRING ``` A function `TooMany()` will: 1. take two parameters: - a string (the search string) - an integer (the maximum value) 2. count the number of strings in the array that exactly match the search string 3. return `TRUE` if the count is greater than the maximum value, otherwise will return `FALSE` ### (a) Write pseudocode for the function `TooMany().` <span class="part-marks">6 marks</span>
Show mark scheme

4(a) [6 marks]

BOOLEAN DECLARE Count, Index : INTEGER  Count 0  FOR Index 1 TO 150 IF Data[Index] = Search THEN  Count Count + 1 ENDIF NEXT Index IF Count > Max THEN RETURN TRUE ELSE RETURN FALSE ENDIF ENDFUNCTION MP1 Function heading, ending and return type MP2 Declare Count and Index as integers MP3 Initialise Count MP4 Loop (any type) for 150 iterations MP5 Compare Data element with parameter - if equal, increment Count in a loop MP6 Compare Count with Max and return Boolean in both cases outside the loop

4(b) [3 marks]

MP1 Test for row being even number MP2 Test for either column value equal to Search IF Row MOD 2 = 0 AND __ (Data[Row, 1] = Search OR Data[Row, 2] = Search) THEN ALTERNATIVE using nested : IFs IF Row MOD 2 = 0 THEN IF Data[Row, 1] = Search OR Data[Row, 2] = Search THEN MP3 Selection structure is either: • Single IF statement using AND, or • Two nested IFs using AND, or • Single IF and the use of a two-iteration loop Either of these structures correctly formed scores the mark ALTERNATIVE SOLUTION: A FOR loop using ‘STEP 2’  FOR Row 2 TO 150 / NEXT Row STEP 2 Data[Row, 1] = Search OR Data[Row, 2] = Search) THEN MP1 should be

Q5
Oct/Nov 2023 Paper 2 v2

A global 1D array of integers contains four elements, which are assigned values as shown:

  Mix[1]  1
# ←
  Mix[2]  3
# ←
  Mix[3]  4
# ←
  Mix[4]  2
# ←

A procedure Process() manipulates the values in the array.

The procedure is written in pseudocode:

PROCEDURE Process(Start : INTEGER)
DECLARE Value, Index, Count : INTEGER
Index  Start
# ←
Count  0
# ←
REPEAT
Value  Mix[Index]
# ←
Mix[Index]  Mix[Index] - 1
# ←
Index  Value
# ←
Count  Count + 1
# ←
UNTIL Count = 5
Mix[4]  Count * Index
# ←
ENDPROCEDURE

Complete the trace table on the opposite page by dry running the procedure when it is called as follows:

  CALL Process(3)

6 marks

11
Index Value Count Mix[1] Mix[2] Mix[3] Mix[4]
A global 1D array of integers contains four elements, which are assigned values as shown: ``` Mix[1] 1 # ← Mix[2] 3 # ← Mix[3] 4 # ← Mix[4] 2 # ← ``` A procedure `Process()` manipulates the values in the array. The procedure is written in pseudocode: ``` PROCEDURE Process(Start : INTEGER) DECLARE Value, Index, Count : INTEGER ``` ``` Index Start # ← Count 0 # ← ``` ``` REPEAT Value Mix[Index] # ← Mix[Index] Mix[Index] - 1 # ← Index Value # ← Count Count + 1 # ← UNTIL Count = 5 ``` ``` Mix[4] Count * Index # ← ``` ``` ENDPROCEDURE ``` Complete the trace table on the opposite page by dry running the procedure when it is called as follows: ``` CALL Process(3) ``` <span class="part-marks">6 marks</span> ||||11|||| |---|---|---|---|---|---|---| |**`Index`**|**`Value`**|**`Count`**|**`Mix[1]`**|**`Mix[2]`**|**`Mix[3]`**|**`Mix[4]`**| |||||||| |||||||| |||||||| |||||||| |||||||| |||||||| |||||||| |||||||| |||||||| |||||||| |||||||| |||||||| |||||||| |||||||| |||||||| |||||||| |||||||| |||||||| |||||||| ||||||||
Show mark scheme

5 [6 marks]

One mark for: • Initialisation row • Each iteration of Count 1 to 4 with correct , and array Index Count Mix as shown • Final iteration, Count = 5, correct , and array as shown Index Count Mix plus assignment Mix[4]

Q5
May/Jun 2023 Paper 2 v1
1 20 2 20 3 20 ... 126 30 127 30 128 2
20
20
20
30
30
2
20
20
30
50
30
3
20
20
40
40
40
4
20
20
50
40
50
20
20
3
5
6
60
4
20 4 2 4 70 30
20 20 35 40 46 25

Write pseudocode for procedure Mix() .

Assume Sample and Result are global. 6 marks

|1 20|2 20|3 20|...|126 30|127 30|128 2| |---|---|---|---|---|---|---| |`20`<br>|`20`<br>|`20`<br>||`30`<br>|`30`<br>|`2`<br>| |`20`<br>|`20`<br>|`30`<br>||`50`<br>|`30`<br>|`3`<br>| |`20`<br>|`20`<br>|`40`<br>||`40`<br>|`40`<br>|`4`<br>| |`20`<br>|`20`<br>|`50`<br>||`40`<br>|`50`<br>|`20`<br>| |`20`<br>|`3`<br>|`5`<br>||`6`<br>|`60`<br>|`4`<br>| |`20`|`4`|`2`||`4`|`70`|`30`| ``` 20 20 35 40 46 25 ``` Write pseudocode for procedure `Mix()` . Assume `Sample` and `Result` are global. <span class="part-marks">6 marks</span>
Show mark scheme

5(a)(i)

Reasons include: 1 No working software until late in the life cycle so slower to market than competitors // Does not allow the creation of early versions/prototypes (which can be updated later) 2 More difficult/slower to cope with changes to the requirements // website slower to be updated to reflect new requirements 3 Needs high involvement/feedback of the stake holders /customer / client One mark per point Max 2 marks

5(a)(ii) [3 marks]

Iterative / Rapid Application Development / RAD

5(b) [6 marks]

One mark for Stage Stage: Beta testing Max 2 marks for Description Description: 1 Testing carried out by a small group of (potential) users 2 Users will check that the website/software works as required / works in the real world //User will identify errors in the website/software 3 Users will feedback (problems) / suggestions for improvement 4 Problems / suggestions identified are addressed (before the program is sold) PROCEDURE Mix()

Q6
May/Jun 2023 Paper 2 v1

A video-conferencing program supports up to six users. Speech from each user is sampled and digitised (converted from analogue to digital). Digitised values are stored in array Sample .

The array Sample consists of 6 rows by 128 columns and is of type integer. Each row contains 128 digitised sound samples from one user.

The digitised sound samples from each user are to be processed to produce a single value which will be stored in a 1D array Result of type integer. This process will be implemented by procedure Mix() .

A procedure Mix() will:

  • calculate the average of each of the 6 sound samples in a column

  • ignore sound sample values of 10 or less

  • store the average value in the corresponding position in Result

  • repeat for each column in array Sample

The diagram uses example values to illustrate the process:

Sample:

Result:
A video-conferencing program supports up to six users. Speech from each user is sampled and digitised (converted from analogue to digital). Digitised values are stored in array `Sample` . The array `Sample` consists of 6 rows by 128 columns and is of type integer. Each row contains 128 digitised sound samples from one user. The digitised sound samples from each user are to be processed to produce a single value which will be stored in a 1D array `Result` of type integer. This process will be implemented by procedure `Mix()` . A procedure `Mix()` will: - calculate the average of each of the 6 sound samples in a column - ignore sound sample values of 10 or less - store the average value in the corresponding position in `Result` - repeat for each column in array `Sample` The diagram uses example values to illustrate the process: ``` Sample: Result: ```
Show mark scheme

6 [3 marks]

DECLARE Count, Total ThisNum : INTEGER DECLARE ThisUser, ThisSample : INTEGER  FOR ThisSample 1 TO 128  Count 0  Total 0  FOR ThisUser 1 TO 6 IF Sample[ThisUser, ThisSample] > 10 THEN  Count Count + 1  Total Total + Sample[ThisUser, ThisSample] ENDIF NEXT ThisUser  Result[ThisSample] INT(Total / Count) NEXT ThisSample ENDPROCEDURE Mark as follows: 1 Declaration and initialisation before inner loop of and Count Total 2 Outer Loop for 128 iterations 3 Inner loop for six iterations 4 Test for sample > 10 in a loop 5 and if true sum and increment Total Count 6 Calculate average value and assign to array after inner loop Result and within outer loop 7 Use of to convert average to integer INT()/ DIV Max 6 Marks

Q1
May/Jun 2023 Paper 2 v3

The following pseudocode represents part of the algorithm for a program.

Line numbers are for reference only.

    10  DECLARE Sheet4 : ARRAY[1:2, 1:50] OF INTEGER
    …

    100 FOR PCount  0 TO 49
    101   Sheet4[1, PCount]  0
    102   Sheet4[2, PCount]  47
    103 NEXT PCount

(a) The pseudocode contains references to an array. 3 marks

Complete the table by writing the answer for each row.

Answer
The dimension of the array
The name of the variable used as an array index
The number of elements in the array

(b) The pseudocode contains two errors. One error is that variable PCount has not been declared. 2 marks

Identify the other error and state the line number where it occurs.

Error

Line number

(c) The pseudocode does not include a declaration for PCount . 1 mark

State the data type that should be used in the declaration.

The following pseudocode represents part of the algorithm for a program. Line numbers are for reference only. ``` 10 DECLARE Sheet4 : ARRAY[1:2, 1:50] OF INTEGER … 100 FOR PCount 0 TO 49 101 Sheet4[1, PCount] 0 102 Sheet4[2, PCount] 47 103 NEXT PCount ``` ### (a) The pseudocode contains references to an array. <span class="part-marks">3 marks</span> Complete the table by writing the answer for each row. ||Answer| |---|---| |The dimension of the array|| |The name of the variable used as an array index|| |The number of elements in the array|| ### (b) The pseudocode contains two errors. One error is that variable `PCount` has not been declared. <span class="part-marks">2 marks</span> Identify the **other** error **and** state the line number where it occurs. Error Line number ### (c) The pseudocode does not include a declaration for `PCount` . <span class="part-marks">1 mark</span> State the data type that should be used in the declaration.
Show mark scheme

1(a) [3 marks]

2 The dimension of the array PCount The name of the variable used as an array index 100 The number of elements in the array

1(b) [2 marks]

One mark per point:  The (second dimension/index of the) array is declared from 1 to 50 but the loop runs from 0 to 49  Line number: 10 / 100 / 101 / 102

1(c) [1 mark]

Integer

1(d) [4 marks]

One mark for each of rows 2 - 5 Pseudocode statement Input Process Output INPUT MyChoice  OUTPUT FirstName & LastName   WRITEFILE OutputFile, TextLine  READFILE MyFile, TextLine    Result SQRT(NextNum)

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.

Q1
May/Jun 2023 Paper 4 v2

A 1D array needs to store the names of 10 animals.

(a) Write program code to declare the global string array Animals to store 10 items. 2 marks

Save your program as Question1_J2023 .

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

(b) The main program needs to store the following animals in the array: 2 marks

horse lion rabbit mouse bird deer whale elephant kangaroo tiger

Write program code to store these animal names in the array. The names must be in lower case and stored in the order given in the list.

Save your program.

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

A 1D array needs to store the names of 10 animals. ### (a) Write program code to declare the global string array `Animals` to store 10 items. <span class="part-marks">2 marks</span> Save your program as **Question1_J2023** . Copy and paste the program code into **part 1(a)** in the evidence document. ### (b) The main program needs to store the following animals in the array: <span class="part-marks">2 marks</span> horse lion rabbit mouse bird deer whale elephant kangaroo tiger Write program code to store these animal names in the array. The names must be in lower case and stored in the order given in the list. 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 array named Animals 10 string elements Example Program code: public static String[] Animals = new String[10]; VB.NET Dim Animals(9) As String Python global Animals #array 10 elements string

1(b)

Python #main Animals = [] Animals.append("horse") Animals.append("lion") Animals.append("rabbit") Animals.append("mouse") Animals.append("bird") Animals.append("deer") Animals.append("whale") Animals.append("elephant") Animals.append("kangaroo") Animals.append("tiger")

1(c)

if(Animals[Y].charAt(0) < Animals[Y+1].charAt(0)){ Temp = Animals[Y]; Animals[Y] = Animals[Y+1]; Animals[Y+1] = Temp; } } VB.NET Sub SortDescending() Dim ArrayLength As Integer = 10 Dim Temp As String = "" For X = 0 To ArrayLength - 1 For Y = 0 To ArrayLength - X - 2 If Left(Animals(Y), 1) < Left(Animals(Y + 1), 1) Then Temp = Animals(Y) Animals(Y) = Animals(Y + 1) Animals(Y + 1) = Temp End If Next Next End Sub Python def SortDescending(): ArrayLength = 10 for X in range(0, ArrayLength-1): for Y in range(0, ArrayLength-X-1): if(Animals[Y][0] < Animals[Y+1][0]): Temp = Animals[Y] Animals[Y] = Animals[Y + 1] Animals[Y + 1] = Temp

1(d)(i) [3 marks]

1 mark each calling the procedure SortDescending() looping through all array elements outputting each array element on a new line Example Program code: SortDescending(); for(Integer X = 0; X < 10; X++){ System.out.println(Animals[X]); VB.NET SortDescending() For X = 0 to 9 Console.WriteLine(Animals(X)) Next X Python SortDescending() for X in range(0, 10): print(Animals[X])

1(d)(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.

Q8
Oct/Nov 2022 Paper 2 v1

A teacher is designing a program to perform simple syntax checks on programs written by students. Student programs are submitted as text files, which are known as project files.

A project file may contain blank lines.

The teacher has defined the first program module as follows:

Module Description
CheckFile() • takes the name of an existing project file as a parameter of type
string
• returnsTRUE if the file is valid (it contains at least 10 non-blank
lines), otherwise returnsFALSE

(a) Write pseudocode for module CheckFile() . 7 marks

Further modules are defined as follows:

Module Description
CheckLine() • takes a line from a project file as a parameter of type string
• returns zero if the line is blank or contains no syntax error,
otherwise returns an error number as an integer
CountErrors() • takes two parameters:


the name of a project file as a string


the maximum number of errors as an integer
• usesCheckFile() to test the project file. Outputs an error
message and ends if the project file is not valid
• callsCheckLine() for each line in the project file
• counts the number of errors
• outputs the number of errors or a warning message if the
maximum number of errors is exceeded

(b) CountErrors() is called to check the project file Jim01Prog.txt and to stop if more than 20 errors are found. 2 marks

Write the pseudocode statement for this call.

(c) Write pseudocode for module CountErrors() . Assume CheckFile() and CheckLine() have been written and can be used in your solution. 8 marks

(d) Module CheckLine() includes a check for syntax errors. 2 marks

Two examples of syntax error that cannot be detected from examining a single line are those involving selection and iteration.

Give two other examples.

1

2

A teacher is designing a program to perform simple syntax checks on programs written by students. Student programs are submitted as text files, which are known as project files. A project file may contain blank lines. The teacher has defined the first program module as follows: |Module|Description| |---|---| |`CheckFile()`|• takes the name of an existing project file as a parameter of type<br>string<br>• returns`TRUE` if the file is valid (it contains at least 10 non-blank<br>lines), otherwise returns`FALSE`| ### (a) Write pseudocode for module `CheckFile()` . <span class="part-marks">7 marks</span> Further modules are defined as follows: |Module|Description| |---|---| |`CheckLine()`|• takes a line from a project file as a parameter of type string<br>• returns zero if the line is blank or contains no syntax error,<br>otherwise returns an error number as an integer| |`CountErrors()`|• takes two parameters:<br> <br>○<br>the name of a project file as a string<br> <br>○<br>the maximum number of errors as an integer<br>• uses`CheckFile()` to test the project file. Outputs an error<br>message and ends if the project file is not valid<br>• calls`CheckLine()` for each line in the project file<br>• counts the number of errors<br>• outputs the number of errors or a warning message if the<br>maximum number of errors is exceeded| ### (b) `CountErrors()` is called to check the project file `Jim01Prog.txt` and to stop if more than 20 errors are found. <span class="part-marks">2 marks</span> Write the pseudocode statement for this call. ### (c) Write pseudocode for module `CountErrors()` . Assume `CheckFile()` and `CheckLine()` have been written and can be used in your solution. <span class="part-marks">8 marks</span> ### (d) Module `CheckLine()` includes a check for syntax errors. <span class="part-marks">2 marks</span> Two examples of syntax error that **cannot** be detected from examining a **single** line are those involving selection and iteration. Give **two other** examples. 1 2
Show mark scheme

8(a) [7 marks]

One mark for each point ( Max 7 ) as follows: 1 Function heading and ending including parameter and return type 2 Declaration and initialisation of local Integer for Count 3 OPEN in READ mode and CLOSE 4 Conditional loop until EOF() 5 Read a line in a loop 6 If non-blank, increment count in a loop 7 Terminate loop when 10 non-blank lines have been read 8 Return Boolean in both cases FUNCTION CheckFile(Thisfile : STRING) RETURNS BOOLEAN DECLARE Valid : BOOLEAN DECLARE ThisLine : STRING DECLARE Count : INTEGER  Count 0  Valid FALSE OPEN ThisFile FOR READ WHILE NOT EOF(ThisFile) AND Valid = FALSE READFILE ThisFile, ThisLine IF ThisLine <> "" THEN  Count Count + 1 IF Count > 9 THEN  Valid TRUE ENDIF ENDIF ENDWHILE CLOSEFILE ThisFile RETURN Valid ENDFUNCTION CALL CountErrors("Jim01Prog.txt", 20)

8(b) [2 marks]

One mark for each: 1 Module name, at least one parameter in brackets and one parameter correct 2 Completely correct statement

8(c) [8 marks]

Mark as follows: 1 Procedure heading and ending including parameters 2 Declaration and initialisation of local Integer value for ErrCount 3 Use of , output message and terminate if it returns CheckFile() FALSE 4 Conditional loop until EOF() 5 ...or

ErrCount MaxErrors 6 Read line and use as parameter to in a loop CheckLine() 7 Test return value and increment if non-zero in a loop ErrCount 8 Output either message once only as appropriate PROCEDURE CountErrors(ThisFile : STRING, MaxErrors : INTEGER) DECLARE ErrCount, ThisError : INTEGER DECLARE ThisLine : STRING  ErrCount 0 IF CheckFile(ThisFile) = FALSE THEN OUTPUT "That program file is not valid" ELSE OPEN ThisFile FOR READ REPEAT READFILE, ThisFile, ThisLine  ThisError CheckLine(ThisLine) IF ThisError <> 0 THEN  ErrCount ErrCount + 1 ENDIF UNTIL ErrCount > MaxErrors OR EOF(ThisFile) IF EOF(ThisFile) = FALSE THEN OUTPUT "Check terminated – too many errors" ELSE OUTPUT "There were ", ErrCount, " errors." ENDIF CLOSEFILE ThisFile ENDIF ENDPROCEDURE

8(d) [2 marks]

One mark for each ( Max 2 ): Examples: 1 Incorrect block structure. Missing keyword denoting part of block (for example ) ENDPROCEDURE, ENDFUNCTION, ENDTYPE 2 Data type errors, for example, assigning an integer value to a string 3 Identifier used before it is declared 4 Incorrect parameter use

Q3
Oct/Nov 2022 Paper 2 v2

A stack is used in a program to store string data which needs to be accessed in several modules.

(a) A stack is an example of an Abstract Data Type (ADT). 3 marks

Identify one other example of an ADT and describe its main features.

Example

Features

(b) Explain how the stack can be implemented using an array. 5 marks

A stack is used in a program to store string data which needs to be accessed in several modules. ### (a) A stack is an example of an Abstract Data Type (ADT). <span class="part-marks">3 marks</span> Identify **one** **other** example of an ADT **and** describe its main features. Example Features ### (b) Explain how the stack can be implemented using an array. <span class="part-marks">5 marks</span>
Show mark scheme

3(a) [3 marks]

One mark for name, Max two for features ( Max 3 in total ) Name: Queue Features: 1 Each queue element contains one data item 2 A Pointer to the front / start of the queue 3 A Pointer to the back / end of the queue 4 Data is added at back / end and removed from front / start // works on a FIFO basis 5 May be circular ALTERNATIVE: Name: Linked List Features: 1 Each node contains data and a pointer to the next node 2 A Pointer to the start of the list 3 Last node in the list has a null pointer 4 Data may be added / removed by manipulating pointers (not moving data) 5 Nodes are traversed in a specific sequence 6 Unused nodes are stored on a free list // a free-list pointer to the Free List

3(b) [5 marks]

One mark per point ( Max 5 ): 1 Declare a (1D) array of data type STRING 2 The number of elements in that array corresponds to the size of the required stack 3 Declare an integer / variable for StackPointer 4. Declare an integer / variable for the size of the stack // for the max value of StackPointer 5 Use the as an index to the array StackPointer 6 Pointers and variables initialised to indicate empty stack 7 Store each item on the stack as one array element / Each stack item maps to one array element 8 Attempt to describe Push and Pop operations 9 Push and Pop routines need to check for full or empty conditions

3(c) [5 marks]

One mark for each: 1 Data 'After Group 1' (as shown, including blank cells) 2 Data 'After Group 2' (as shown, including blank cells) 3 Data 'After Group 3' (as shown, including blank cells) 4 SP 'After Group 1' pointing to location 955 5 Final two SPs pointing to locations 952 and 954

Q3
Oct/Nov 2022 Paper 2 v3

An algorithm is needed to process a sequence of numbers. Numbers may be positive or negative and may be integer or decimal.

The algorithm will:

  • prompt and input one number at a time until the value zero is input

  • sum the negative numbers

  • sum the positive numbers

  • when zero is input, output the two sum values and then end.

Describe the algorithm needed. Do not include pseudocode statements in your answer. 5 marks

An algorithm is needed to process a sequence of numbers. Numbers may be positive or negative and may be integer or decimal. The algorithm will: - prompt and input one number at a time until the value zero is input - sum the negative numbers - sum the positive numbers - when zero is input, output the two sum values and then end. Describe the algorithm needed. Do **not** include pseudocode statements in your answer. <span class="part-marks">5 marks</span>
Show mark scheme

3 [5 marks]

One mark per point, for example: 1 Declare two ( variables for the two sum values AND initialise both REAL) to zero 2 Prompt AND Input a number 3 If number greater than zero add to positive sum and If number less than zero add to negative sum 4 Repeat from step 2 if number not zero 5 After loop the Output and SumPos SumNeg

Q5
May/Jun 2022 Paper 2 v3

A program will store attendance data about each employee of a company.

The data will be held in a reco shown: ord structure of type Employee e. The fields that will be needed are as
Field Typical value Comment
EmployeeNumber 123 A numeric value starting from 1
Name "Smith,Eric" Format: ','
Department "1B" May contain letters and numbers
Born 13/02/2006 Must not be before 04/02/1957
Attendance 97.40 Represents a percentage

(a) (i) Write pseudocode to declare the record structure for type Employee . 4 marks

(ii) A 1D array Staff containing 500 elements will be used to store the employee records. 2 marks

Write pseudocode to declare the Staff array.

(b) There may be more records in the array than there are employees in the company. In this case, some records of the array will be unused.

(i) State why it is good practice to have a standard way to indicate unused array elements. 1 mark

(ii) Give one way of indicating an unused record in the Staff array. 1 mark

A program will store attendance data about each employee of a company. |The data will be held in a reco shown:|ord structure of type Employee|e. The fields that will be needed are as| |---|---|---| |**Field**|**Typical value**|**Comment**| |`EmployeeNumber`|`123`|A numeric value starting from 1| |`Name`|`"Smith,Eric"`|Format: <last name>','<first name>| |`Department`|`"1B"`|May contain letters and numbers| |`Born`|`13/02/2006`|Must not be before 04/02/1957| |`Attendance`|`97.40`|Represents a percentage| **(a) (i)** Write pseudocode to declare the record structure for type `Employee` . <span class="part-marks">4 marks</span> #### (ii) A 1D array `Staff` containing 500 elements will be used to store the employee records. <span class="part-marks">2 marks</span> Write pseudocode to declare the `Staff` array. ### (b) There may be more records in the array than there are employees in the company. In this case, some records of the array will be unused. #### (i) State why it is good practice to have a standard way to indicate unused array elements. <span class="part-marks">1 mark</span> #### (ii) Give **one** way of indicating an unused record in the `Staff` array. <span class="part-marks">1 mark</span>
Show mark scheme

5(a)(i)

DECLARE EmployeeNumber : INTEGER DECLARE Name : STRING DECLARE Department : STRING DECLARE Born : DATE DECLARE Attendance : REAL ENDTYPE One mark for each: 1. and TYPE Employee ENDTYPE 2. and and Fields: EmployeeNumber Name Department 3. Field: Born 4. Field: Attendance DECLARE Staff : ARRAY [1:500] OF Employee

5(a)(ii) [2 marks]

One mark per underlined phrase

5(b)(i) [1 mark]

Example answers to Max 1 :  So that unused elements may be recognised when processing / searching  Otherwise the element may contain old / unexpected data

5(b)(ii) [1 mark]

Use of any 'impossible' field value, for example:  An field. e.g. < 1 EmployeeNumber  An empty string / impossible string e.g. "EMPTY" for name or department  DOB a long time ago...  Zero / Negative value for attendance PROCEDURE Absentees()

5(c) [6 marks]

DECLARE Index : INTEGER  FOR Index 1 TO 500 IF Staff[Index].EmployeeNumber <> −1 THEN // not empty IF Staff[Index].Attendance <= 90 THEN OUTPUT Staff[Index].EmployeeNumber OUTPUT Staff[Index].Name ENDIF ENDIF NEXT Index ENDPROCEDURE Marks as follows to Max 4 : 1 Procedure heading and ending and declaration of loop counter 2 loop through 500 elements 3 attempt to skip unused element 4 test in a loop <= 90 Staff[Index].Attendance 5 if so, output and fields in a loop Name EmployeeNumber FUNCTION Factorial(ThisNum : INTEGER) RETURNS INTEGER

Q2
May/Jun 2022 Paper 4 v1

A computer game is being developed using object-oriented programming.

One element of the game is a balloon. This is designed as the class Balloon. The class has the following attributes and methods. Balloon
Balloon Balloon
Health : INTEGER
Colour : STRING
DefenceItem : STRING
The health of the balloon
The colour of the balloon
The item the balloon uses to defend itself
Constructor()
ChangeHealth()
GetDefenceItem()
CheckHealth()
Initialises the defence item and colour using the
parameters
Initialises health to 100
Takes the change as a parameter and adds this to the
health
Returns the defence item of the object
If the health is 0 or less, it returnsTRUE, otherwise it
returnsFALSE

(a) The constructor takes the name of the defence item and the balloon’s colour as parameters and sets these to the attributes. The health is initialised to 100 . 5 marks

Write program code to declare the class Balloon 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 include attribute declarations using comments.

Save your program as Question2_J2022 .

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

(b) The get method GetDefenceItem() returns the defence item of the object. 2 marks

Amend your program code to include the get method GetDefenceItem() .

Save your program.

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

(c) The object’s method ChangeHealth() takes an integer number as a parameter and adds this to the health attribute of the object. 2 marks

Amend your program code to include the method ChangeHealth() .

Save your program.

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

(d) The object’s method CheckHealth() returns TRUE if the health of the object is 0 or less (no health remaining) and returns FALSE otherwise (health remaining). 2 marks

Amend your program code to include the method CheckHealth() .

Save your program.

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

(e) Amend the main program to: 3 marks

  • take as input a defence item and colour from the user

  • create a new balloon with the identifier Balloon1 using the data input.

Save your program.

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

(f) The function Defend() : 8 marks

  • takes a balloon object as a parameter

  • takes as input the strength of an opponent from the user

  • uses the ChangeHealth() method to subtract the strength input from the object’s health

  • outputs the defence item of the balloon

  • checks the health of the object and outputs an appropriate message if it has no health remaining, or if it has health remaining

  • returns the amended balloon object.

Write program code to declare the function Defend() .

Save your program.

Copy and paste the program code into part 2(f) in the evidence document. (g) (i) Amend the main program to call the function Defend() . 2 marks

Save your program.

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

(ii) Test your program using the following inputs: 1 mark

  • balloon defence method "Shield"

  • balloon colour "Red"

  • strength of opponent 50

Take a screenshot to show the output.

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

A computer game is being developed using object-oriented programming. |One element of the game is a balloon. This is designed as the class Balloon. The class has the following attributes and methods. Balloon|| |---|---| |**`Balloon`**|**`Balloon`**| |`Health : INTEGER`<br>`Colour : STRING`<br>`DefenceItem : STRING`|The health of the balloon<br>The colour of the balloon<br>The item the balloon uses to defend itself| |`Constructor()`<br>`ChangeHealth()`<br>`GetDefenceItem()`<br>`CheckHealth()`|Initialises the defence item and colour using the<br>parameters<br>Initialises health to 100<br>Takes the change as a parameter and adds this to the<br>health<br>Returns the defence item of the object<br>If the health is 0 or less, it returns`TRUE`, otherwise it<br>returns`FALSE`| ### (a) The constructor takes the name of the defence item and the balloon’s colour as parameters and sets these to the attributes. The health is initialised to `100` . <span class="part-marks">5 marks</span> Write program code to declare the class `Balloon` 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 include attribute declarations using comments. Save your program as **Question2_J2022** . Copy and paste the program code into **part 2(a)** in the evidence document. ### (b) The get method `GetDefenceItem()` returns the defence item of the object. <span class="part-marks">2 marks</span> Amend your program code to include the get method `GetDefenceItem()` . Save your program. Copy and paste the program code into **part 2(b)** in the evidence document. ### (c) The object’s method `ChangeHealth()` takes an integer number as a parameter and adds this to the health attribute of the object. <span class="part-marks">2 marks</span> Amend your program code to include the method `ChangeHealth()` . Save your program. Copy and paste the program code into **part 2(c)** in the evidence document. ### (d) The object’s method `CheckHealth()` returns `TRUE` if the health of the object is 0 or less (no health remaining) and returns `FALSE` otherwise (health remaining). <span class="part-marks">2 marks</span> Amend your program code to include the method `CheckHealth()` . Save your program. Copy and paste the program code into **part 2(d)** in the evidence document. ### (e) Amend the main program to: <span class="part-marks">3 marks</span> - take as input a defence item and colour from the user - create a new balloon with the identifier `Balloon1` using the data input. Save your program. Copy and paste the program code into **part 2(e)** in the evidence document. ### (f) The function `Defend()` : <span class="part-marks">8 marks</span> - takes a balloon object as a parameter - takes as input the strength of an opponent from the user - uses the `ChangeHealth()` method to subtract the strength input from the object’s health - outputs the defence item of the balloon - checks the health of the object and outputs an appropriate message if it has no health remaining, or if it has health remaining - returns the amended balloon object. Write program code to declare the function `Defend()` . Save your program. Copy and paste the program code into **part 2(f)** in the evidence document. **(g) (i)** Amend the main program to call the function `Defend()` . <span class="part-marks">2 marks</span> Save your program. Copy and paste the program code into **part 2(g)(i)** in the evidence document. #### (ii) Test your program using the following inputs: <span class="part-marks">1 mark</span> - balloon defence method `"Shield"` - balloon colour `"Red"` - strength of opponent `50` Take a screenshot to show the output. Copy and paste the screenshot into **part 2(g)(ii)** in the evidence document.
Show mark scheme

2(a)

VB.NET Class balloon Private Health As Integer Private Colour As String Private DefenceItem As String Public Sub New(PDefenceItem, PColour) Health = 100 Colour = PColour DefenceItem = PDefenceItem End Sub End Class

2(b) [2 marks]

1 mark per mark point get header and close with no parameter … … returning defence item attribute Example program code: public String GetDefenceItem(){ return DefenceItem; Python def GetDefenceItem(self): return self.__DefenceItem VB.NET Public Function GetDefenceItem() Return DefenceItem End Function

2(c) [2 marks]

1 mark per mark point procedure header and close taking 1 parameter … … adding parameter value to health attribute Example program code: public void ChangeHealth(Integer Change){ Health = Health + Change; Python def ChangeHealth(self, Change): self.__Health = self.__Health + Change VB.NET Public Sub ChangeHealth(Change) Health = Health + Change End Sub

2(d) [2 marks]

1 mark per mark point method header and close and checking if health attribute is <= 0 Returning TRUE if health attribute <= 0 and returning FALSE otherwise Example program code: public Boolean CheckHealth(){ if(Health <= 0){ return true; }else{ return false; Python def CheckHealth(self): if self.__Health <= 0: return True else: return False VB.NET Function CheckHealth() If Health <= 0 Then Return True Else Return False End If End Function

2(e) [3 marks]

1 mark per mark point take as input defence method and colour (2 strings) instantiating new balloon object with identifier Balloon1 … … with both input values as parameters Example program code: public static void main(String[] args){ Scanner scanner = new Scanner(System.in); System.out.println("Enter balloon defence method"); String Method = scanner.nextLine(); System.out.println("Enter the balloon colour"); String Colour = scanner.nextLine(); Balloon Balloon1 = new Balloon(Method, Colour); Python Method = input("Enter balloon defence method ") Colour = input("Enter the balloon colour ") Balloon1 = Balloon(Method, Colour) VB.NET Sub Main() Console.WriteLine("Enter balloon defence method") Dim Method As String = Console.ReadLine Console.WriteLine("Enter the balloons colour") Dim Colour As String = Console.ReadLine Dim Balloon1 As Balloon = New Balloon(Method, Colour) End Sub

2(f)

Python def Defend(MyBalloon): Strength = int(input("Enter the strength of opponent")) MyBalloon.VhangeHealth(-Strength) print("You defended with ", str(MyBalloon.GetDefenceItem())) if(MyBalloon.CheckHealth() == True): print("Defence failed") else: print("Defence succeeded") return MyBalloon VB.NET Function Defend(MyBalloon) Console.WriteLine("Enter the strength of opponent") Dim Strength As Integer = Console.ReadLine MyBalloon.ChangeHealth(-Strength) Console.WriteLine("You defended with " & MyBalloon.GetDefenceItem) If (MyBalloon.CheckHealth() = True) Then Console.WriteLine("Defence failed") Else Console.WriteLine("Defence succeeded") End If Return MyBalloon End Function

2(g)(i) [2 marks]

1 mark each calling Defend with balloon object … … and stores return value over object Example program code: Balloon1 = Defend(Balloon1); Python Balloon1 = Defend(Balloon1) VB.NET Balloon1 = Defend(Balloon1)

2(g)(ii) [1 mark]

1 mark for screenshot with: Shield, Red and 50 input Output stating their defence item was Shield Output says health is not 0 (in some manner)

Q2
May/Jun 2022 Paper 4 v2

A 2D array stores data entered by a user.

(a) The main program declares a 2D array of 10 by 10 integer elements. 4 marks

The array is initialised with a random number between 1 and 100 in each element.

Write program code for the main program.

Save your program as Question2_J22 .

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

(b) The following bubble sort pseudocode algorithm sorts the data in the first dimension of the 2D array into ascending numerical order.

ArrayLength 10

FOR X 0 TO ArrayLength - 1

FOR Y 0 TO ArrayLength - 2

FOR Z 0 TO ArrayLength - Y - 2

IF ArrayData[X, Z] > ArrayData[X, Z + 1] THEN

    TempValue  ArrayData[X, Z]

ArrayData[X, Z] ArrayData[X, Z+1]

ArrayData[X, Z + 1] TempValue

ENDIF

NEXT Z

NEXT Y

NEXT X

(i) Amend your main program by writing program code to implement the bubble sort algorithm after the initialisation of the array elements. 5 marks

You must not use any built-in sorting functions for your programming language.

Save your program.

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

(ii) Write program code for a procedure to output all the values in the 2D array. The values should be output as a 2D grid, with values in rows and columns. 3 marks

Call the procedure before and after your bubble sort code.

Save your program.

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

(iii) Test your program. 1 mark

Take a screenshot to show the output.

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

(c) The following pseudocode function uses recursion to perform a binary search in the first row of the array, for the value SearchValue in the array SearchArray .

The function returns −1 if the item was not found, or it returns the index where it is found.

There are six incomplete statements.

FUNCTION BinarySearch(SearchArray, Lower, Upper, SearchValue)RETURNS INTEGER

IF Upper >= Lower THEN

Mid (Lower + (Upper – 1)) DIV …………………………………

IF SearchArray[0, Mid] = ………………………………… THEN

RETURN …………………………………

ELSE

IF SearchArray[0, Mid] > SearchValue THEN

RETURN BinarySearch(SearchArray, …………………………………, Mid – 1,

                                    SearchValue)
ELSE

RETURN BinarySearch(SearchArray, Mid + 1, …………………………………,

                                    SearchValue)

ENDIF

ENDIF

ENDIF

RETURN …………………………………

ENDFUNCTION

Note: the arithmetic operator DIV performs integer division, e.g. the result of 10 DIV 3 will be 3 .

(i) Write program code for the recursive function BinarySearch() . 8 marks

Save your program.

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

(ii) In the main program, test the function BinarySearch() twice, outputting the returned value each time. 2 marks

One test should be for a number that is in the first line of the array. One test should be for a number that is not in the first line of the array.

Take a screenshot to show the output.

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

A 2D array stores data entered by a user. ### (a) The main program declares a 2D array of 10 by 10 integer elements. <span class="part-marks">4 marks</span> The array is initialised with a random number between 1 and 100 in each element. Write program code for the main program. Save your program as **Question2_J22** . Copy and paste the program code into **part 2(a)** in the evidence document. ### (b) The following bubble sort pseudocode algorithm sorts the data in the first dimension of the 2D array into ascending numerical order. `ArrayLength` 10 `FOR X` 0 TO ArrayLength - 1 `FOR Y` 0 TO ArrayLength - 2 `FOR Z` 0 TO ArrayLength - Y - 2 IF ArrayData[X, Z] > ArrayData[X, Z + 1] THEN ``` TempValue ArrayData[X, Z] ``` `ArrayData[X, Z]` ArrayData[X, Z+1] ArrayData[X, Z + 1] `TempValue` ENDIF NEXT Z NEXT Y NEXT X #### (i) Amend your main program by writing program code to implement the bubble sort algorithm after the initialisation of the array elements. <span class="part-marks">5 marks</span> You must **not** use any built-in sorting functions for your programming language. Save your program. Copy and paste the program code into **part 2(b)(i)** in the evidence document. #### (ii) Write program code for a procedure to output all the values in the 2D array. The values should be output as a 2D grid, with values in rows and columns. <span class="part-marks">3 marks</span> Call the procedure before and after your bubble sort code. Save your program. Copy and paste the program code into **part 2(b)(ii)** in the evidence document. #### (iii) Test your program. <span class="part-marks">1 mark</span> Take a screenshot to show the output. Copy and paste the screenshot into **part 2(b)(iii)** in the evidence document. ### (c) The following pseudocode function uses recursion to perform a binary search in the first row of the array, for the value `SearchValue` in the array `SearchArray` . The function returns −1 if the item was not found, or it returns the index where it is found. There are **six** incomplete statements. FUNCTION BinarySearch(SearchArray, Lower, Upper, SearchValue)RETURNS INTEGER IF Upper >= Lower THEN `Mid` (Lower + (Upper – 1)) DIV ………………………………… IF SearchArray[0, Mid] = ………………………………… THEN RETURN ………………………………… ``` ELSE ``` IF SearchArray[0, Mid] > SearchValue THEN RETURN BinarySearch(SearchArray, …………………………………, Mid – 1, ``` SearchValue) ``` ``` ELSE ``` RETURN BinarySearch(SearchArray, Mid + 1, …………………………………, ``` SearchValue) ``` ENDIF ENDIF ENDIF RETURN ………………………………… ENDFUNCTION Note: the arithmetic operator `DIV` performs integer division, e.g. the result of 10 DIV 3 will be 3 . #### (i) Write program code for the recursive function BinarySearch() . <span class="part-marks">8 marks</span> Save your program. Copy and paste the program code into **part 2(c)(i)** in the evidence document. #### (ii) In the main program, test the function BinarySearch() twice, outputting the returned value each time. <span class="part-marks">2 marks</span> One test should be for a number that is in the first line of the array. One test should be for a number that is not in the first line of the array. Take a screenshot to show the output. Copy and paste the screenshot into **part 2(c)(ii)** in the evidence document.
Show mark scheme

2(a)

import java.util.Scanner; import java.util.Random; public static Integer[][] ArrayData; public static void main(String args[]){ Random Rand = new Random(); ArrayData = new Integer[10][10]; for(int x=0; x < 10; x++){ for(int y = 0; y < 10; y++){ ArrayData[x][y] = Rand.nextInt(100);} } }

2(b)(i)

Integer ArrayLength = 10; for(int X = 0; X < ArrayLength; X++){ for(int Y = 0; Y < ArrayLength; Y++){ for(int Z = 0; Z < ArrayLength - Y - 1; Z++){ if(ArrayData[X][Z] > ArrayData[X][Z + 1]){ TempNumber = ArrayData[X][Z]; ArrayData[X][Z] = ArrayData[X][Z+1]; ArrayData[X][Z + 1] = TempNumber; } }

2(b)(ii)

TempNumber = ArrayData[X][Z]; ArrayData[X][Z] = ArrayData[X][Z+1]; ArrayData[X][Z + 1] = TempNumber; } } } } System.out.println("After"); PrintArray(ArrayData);

2(b)(iii) [1 mark]

1 mark for output showing array unsorted and then sorted on 1 of the dimensions

2(c)(i)

public static Integer BinarySearch(Integer[][] SearchArray, Integer Lower, Integer Upper, Integer SearchValue){ Integer Mid = 0; If Upper >= 0 { Mid = (Lower + (Upper - 1)) / 2 ; If SearchArray[0][Mid] == SearchValue ){ return Mid ; }else if SearchArray[0][Mid] > SearchValue { return BinarySearch(SearchArray, Lower , Mid-1, SearchValue); }else{ return BinarySearch(SearchArray, Mid+1, Upper , SearchValue); } } return -1 ; }

2(c)(ii) [2 marks]

1 mark per mark point screenshot outputting the index when Number is found screenshot outputting –1 with a Number not found

Q2
May/Jun 2022 Paper 4 v3

A computer game is being developed using object-oriented programming.

One element of the game is a balloon. This is designed as the class Balloon. The class has the following attributes and methods. Balloon
Balloon Balloon
Health : INTEGER
Colour : STRING
DefenceItem : STRING
The health of the balloon
The colour of the balloon
The item the balloon uses to defend itself
Constructor()
ChangeHealth()
GetDefenceItem()
CheckHealth()
Initialises the defence item and colour using the
parameters
Initialises health to 100
Takes the change as a parameter and adds this to the
health
Returns the defence item of the object
If the health is 0 or less, it returnsTRUE, otherwise it
returnsFALSE

(a) The constructor takes the name of the defence item and the balloon’s colour as parameters and sets these to the attributes. The health is initialised to 100 . 5 marks

Write program code to declare the class Balloon 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 include attribute declarations using comments.

Save your program as Question2_J2022 .

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

(b) The get method GetDefenceItem() returns the defence item of the object. 2 marks

Amend your program code to include the get method GetDefenceItem() .

Save your program.

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

(c) The object’s method ChangeHealth() takes an integer number as a parameter and adds this to the health attribute of the object. 2 marks

Amend your program code to include the method ChangeHealth() .

Save your program.

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

(d) The object’s method CheckHealth() returns TRUE if the health of the object is 0 or less (no health remaining) and returns FALSE otherwise (health remaining). 2 marks

Amend your program code to include the method CheckHealth() .

Save your program.

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

(e) Amend the main program to: 3 marks

  • take as input a defence item and colour from the user

  • create a new balloon with the identifier Balloon1 using the data input.

Save your program.

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

(f) The function Defend() : 8 marks

  • takes a balloon object as a parameter

  • takes as input the strength of an opponent from the user

  • uses the ChangeHealth() method to subtract the strength input from the object’s health

  • outputs the defence item of the balloon

  • checks the health of the object and outputs an appropriate message if it has no health remaining, or if it has health remaining

  • returns the amended balloon object.

Write program code to declare the function Defend() .

Save your program.

Copy and paste the program code into part 2(f) in the evidence document. (g) (i) Amend the main program to call the function Defend() . 2 marks

Save your program.

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

(ii) Test your program using the following inputs: 1 mark

  • balloon defence method "Shield"

  • balloon colour "Red"

  • strength of opponent 50

Take a screenshot to show the output.

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

A computer game is being developed using object-oriented programming. |One element of the game is a balloon. This is designed as the class Balloon. The class has the following attributes and methods. Balloon|| |---|---| |**`Balloon`**|**`Balloon`**| |`Health : INTEGER`<br>`Colour : STRING`<br>`DefenceItem : STRING`|The health of the balloon<br>The colour of the balloon<br>The item the balloon uses to defend itself| |`Constructor()`<br>`ChangeHealth()`<br>`GetDefenceItem()`<br>`CheckHealth()`|Initialises the defence item and colour using the<br>parameters<br>Initialises health to 100<br>Takes the change as a parameter and adds this to the<br>health<br>Returns the defence item of the object<br>If the health is 0 or less, it returns`TRUE`, otherwise it<br>returns`FALSE`| ### (a) The constructor takes the name of the defence item and the balloon’s colour as parameters and sets these to the attributes. The health is initialised to `100` . <span class="part-marks">5 marks</span> Write program code to declare the class `Balloon` 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 include attribute declarations using comments. Save your program as **Question2_J2022** . Copy and paste the program code into **part 2(a)** in the evidence document. ### (b) The get method `GetDefenceItem()` returns the defence item of the object. <span class="part-marks">2 marks</span> Amend your program code to include the get method `GetDefenceItem()` . Save your program. Copy and paste the program code into **part 2(b)** in the evidence document. ### (c) The object’s method `ChangeHealth()` takes an integer number as a parameter and adds this to the health attribute of the object. <span class="part-marks">2 marks</span> Amend your program code to include the method `ChangeHealth()` . Save your program. Copy and paste the program code into **part 2(c)** in the evidence document. ### (d) The object’s method `CheckHealth()` returns `TRUE` if the health of the object is 0 or less (no health remaining) and returns `FALSE` otherwise (health remaining). <span class="part-marks">2 marks</span> Amend your program code to include the method `CheckHealth()` . Save your program. Copy and paste the program code into **part 2(d)** in the evidence document. ### (e) Amend the main program to: <span class="part-marks">3 marks</span> - take as input a defence item and colour from the user - create a new balloon with the identifier `Balloon1` using the data input. Save your program. Copy and paste the program code into **part 2(e)** in the evidence document. ### (f) The function `Defend()` : <span class="part-marks">8 marks</span> - takes a balloon object as a parameter - takes as input the strength of an opponent from the user - uses the `ChangeHealth()` method to subtract the strength input from the object’s health - outputs the defence item of the balloon - checks the health of the object and outputs an appropriate message if it has no health remaining, or if it has health remaining - returns the amended balloon object. Write program code to declare the function `Defend()` . Save your program. Copy and paste the program code into **part 2(f)** in the evidence document. **(g) (i)** Amend the main program to call the function `Defend()` . <span class="part-marks">2 marks</span> Save your program. Copy and paste the program code into **part 2(g)(i)** in the evidence document. #### (ii) Test your program using the following inputs: <span class="part-marks">1 mark</span> - balloon defence method `"Shield"` - balloon colour `"Red"` - strength of opponent `50` Take a screenshot to show the output. Copy and paste the screenshot into **part 2(g)(ii)** in the evidence document.
Show mark scheme

2(a)

VB.NET Class balloon Private Health As Integer Private Colour As String Private DefenceItem As String Public Sub New(PDefenceItem, PColour) Health = 100 Colour = PColour DefenceItem = PDefenceItem End Sub End Class

2(b) [2 marks]

1 mark per mark point get header and close with no parameter … … returning defence item attribute Example program code: public String GetDefenceItem(){ return DefenceItem; Python def GetDefenceItem(self): return self.__DefenceItem VB.NET Public Function GetDefenceItem() Return DefenceItem End Function

2(c) [2 marks]

1 mark per mark point procedure header and close taking 1 parameter … … adding parameter value to health attribute Example program code: public void ChangeHealth(Integer Change){ Health = Health + Change; Python def ChangeHealth(self, Change): self.__Health = self.__Health + Change VB.NET Public Sub ChangeHealth(Change) Health = Health + Change End Sub

2(d) [2 marks]

1 mark per mark point method header and close and checking if health attribute is <= 0 Returning TRUE if health attribute <= 0 and returning FALSE otherwise Example program code: public Boolean CheckHealth(){ if(Health <= 0){ return true; }else{ return false; Python def CheckHealth(self): if self.__Health <= 0: return True else: return False VB.NET Function CheckHealth() If Health <= 0 Then Return True Else Return False End If End Function

2(e) [3 marks]

1 mark per mark point take as input defence method and colour (2 strings) instantiating new balloon object with identifier Balloon1 … … with both input values as parameters Example program code: public static void main(String[] args){ Scanner scanner = new Scanner(System.in); System.out.println("Enter balloon defence method"); String Method = scanner.nextLine(); System.out.println("Enter the balloon colour"); String Colour = scanner.nextLine(); Balloon Balloon1 = new Balloon(Method, Colour); Python Method = input("Enter balloon defence method ") Colour = input("Enter the balloon colour ") Balloon1 = Balloon(Method, Colour) VB.NET Sub Main() Console.WriteLine("Enter balloon defence method") Dim Method As String = Console.ReadLine Console.WriteLine("Enter the balloons colour") Dim Colour As String = Console.ReadLine Dim Balloon1 As Balloon = New Balloon(Method, Colour) End Sub

2(f)

Python def Defend(MyBalloon): Strength = int(input("Enter the strength of opponent")) MyBalloon.VhangeHealth(-Strength) print("You defended with ", str(MyBalloon.GetDefenceItem())) if(MyBalloon.CheckHealth() == True): print("Defence failed") else: print("Defence succeeded") return MyBalloon VB.NET Function Defend(MyBalloon) Console.WriteLine("Enter the strength of opponent") Dim Strength As Integer = Console.ReadLine MyBalloon.ChangeHealth(-Strength) Console.WriteLine("You defended with " & MyBalloon.GetDefenceItem) If (MyBalloon.CheckHealth() = True) Then Console.WriteLine("Defence failed") Else Console.WriteLine("Defence succeeded") End If Return MyBalloon End Function

2(g)(i) [2 marks]

1 mark each calling Defend with balloon object … … and stores return value over object Example program code: Balloon1 = Defend(Balloon1); Python Balloon1 = Defend(Balloon1) VB.NET Balloon1 = Defend(Balloon1)

2(g)(ii) [1 mark]

1 mark for screenshot with: Shield, Red and 50 input Output stating their defence item was Shield Output says health is not 0 (in some manner)

Q6
Oct/Nov 2021 Paper 2 v1

A mobile phone has a touchscreen. The screen is represented by a grid, divided into 800 rows and 1280 columns.

The grid is represented by a 2D array Screen of type INTEGER . An array element will be set to 0 unless the user touches that part of the screen.

Many array elements are set to 1 by a single touch of a finger or a stylus.

The following diagram shows a simplified touchscreen. The dark line represents a touch to the screen. All grid elements that are wholly or partly inside the outline will be set to 1. These elements are shaded. The element shaded in black represents the centre point.

11

A program is needed to find the coordinates (the row and column) of the centre point. The centre point on the diagram above is row 6, column 11.

Assume:

  • the user may only touch one area at a time

  • screen rotation does not affect the touchscreen.

The programmer has started to define program modules as follows:

Module Description
SetRow()
(generates test
data)
• Called with three parameters of typeINTEGER:
◦a row number
◦the number of pixels to be skipped starting from column 1
◦the number of pixels that should be set to 1
• Sets the required number of pixels to 1
For example,SetRow(3, 8, 5) will give row 3 as in the diagram shown.
SearchInRow()
• Takes two parameters of typeINTEGER:
◦a row number
◦a start column (1 or 1280)
• Searches the given row from the start column (either left to right or right to left)
for the first column that contains an element set to 1
• Returns the column number of the first element in the given row that is set to 1
• Returns −1 if no element is set to 1
SearchInCol() • Takes two parameters of typeINTEGER:
◦a column number
◦a start row (1 or 800)
• Searches the given column from the start row (either up or down) for the first
row that contains an element set to 1
• Returns the row number of the first element in the given column that is set to 1
• Returns −1 if no element is set to 1

(a) Write pseudocode to implement the module SetRow() . 5 marks 8 marks 6 marks

(b) The modul le description of SearchInRow() is provided here for reference.
Module Description
SearchInRow() • Takes two parameters of typeINTEGER:
◦a row number
◦a start column (1 or 1280)
• Searches the given row from the start column (either left to right or right to left)
for the first column that contains an element set to 1
• Returns the column number of the first element in the given row that is set to 1
• Returns −1 if no element is set to 1

Write pseudocode to implement the module SearchInRow() .

(c) The followi ing new module is introduced:
Module Description
GetCentreCol() • Called with a row number as anINTEGER
• UsesSearchInRow() to find the first and last columns in the given row which
have an array element set to 1
• Returns the index of the column midway between the first and last columns
• Returns −1 if no element is set to 1

Write pseudocode to implement the module GetCentreCol() .

A mobile phone has a touchscreen. The screen is represented by a grid, divided into 800 rows and 1280 columns. The grid is represented by a 2D array `Screen` of type `INTEGER` . An array element will be set to 0 unless the user touches that part of the screen. Many array elements are set to 1 by a single touch of a finger or a stylus. The following diagram shows a simplified touchscreen. The dark line represents a touch to the screen. All grid elements that are wholly or partly inside the outline will be set to 1. These elements are shaded. The element shaded in black represents the centre point. |||||||||||11|||||||||||||| |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| A program is needed to find the coordinates (the row and column) of the centre point. The centre point on the diagram above is row 6, column 11. Assume: - the user may only touch one area at a time - screen rotation does not affect the touchscreen. The programmer has started to define program modules as follows: |Module|Description| |---|---| |`SetRow()`<br>(generates test<br>data)|• Called with three parameters of type`INTEGER`:<br> ◦a row number<br> ◦the number of pixels to be skipped starting from column 1<br> ◦the number of pixels that should be set to 1<br>• Sets the required number of pixels to 1<br>For example,`SetRow(3, 8, 5)` will give row 3 as in the diagram shown.| |`SearchInRow()`|<br>• Takes two parameters of type`INTEGER`:<br> ◦a row number<br> ◦a start column (1 or 1280)<br>• Searches the given row from the start column (either left to right or right to left)<br>for the first column that contains an element set to 1<br>• Returns the column number of the first element in the given row that is set to 1<br>• Returns −1 if no element is set to 1| |`SearchInCol()`|• Takes two parameters of type`INTEGER`:<br> ◦a column number<br> ◦a start row (1 or 800)<br>• Searches the given column from the start row (either up or down) for the first<br>row that contains an element set to 1<br>• Returns the row number of the first element in the given column that is set to 1<br>• Returns −1 if no element is set to 1| ### (a) Write pseudocode to implement the module `SetRow()` . <span class="part-marks">5 marks</span> <span class="part-marks">8 marks</span> <span class="part-marks">6 marks</span> |(b) The modul|le description of SearchInRow() is provided here for reference.| |---|---| |**Module**|**Description**| |`SearchInRow()`|• Takes two parameters of type`INTEGER`:<br> ◦a row number<br> ◦a start column (1 or 1280)<br>• Searches the given row from the start column (either left to right or right to left)<br>for the first column that contains an element set to 1<br>• Returns the column number of the first element in the given row that is set to 1<br>• Returns −1 if no element is set to 1| Write pseudocode to implement the module `SearchInRow()` . |(c) The followi|ing new module is introduced:| |---|---| |**Module**|**Description**| |`GetCentreCol()`|• Called with a row number as an`INTEGER`<br>• Uses`SearchInRow()` to find the first and last columns in the given row which<br>have an array element set to 1<br>• Returns the index of the column midway between the first and last columns<br>• Returns −1 if no element is set to 1| Write pseudocode to implement the module `GetCentreCol()` .
Show mark scheme

6(a) [8 marks]

PROCEDURE SetRow(Row, SkipNum, SetNum : INTEGER) DECLARE Col : INTEGER // array is 1280 x 800 ← FOR Col SkipNum + 1 TO SkipNum + SetNum ← Screen[Row, Col] 1 NEXT Index ENDPROCEDURE ALTERNATIVE 1: ← FOR Col 1 TO SetNum ← Screen[Row, SkipNum + Col] 1 NEXT Col ALTERNATIVE 2: WHILE SetNum > 0 ← Screen[Row, SkipNum + SetNum] 1 ← SetNum SetNum - 1 ENDWHILE Mark as follows: 1 Procedure heading and ending including parameters 2 Declaration of local Integer for Col 3 Count-controlled loop with meaningful start number 4 correct stop number 5 Reference Screen Array element and set to 1 in a loop

6(b) [6 marks]

FUNCTION SearchInRow(ThisRow, StartCol : INTEGER) RETURNS INTEGER DECLARE ThisCol, Step : INTEGER DECLARE Found: BOOLEAN // array is 1280 x 800 ← Found FALSE ← ThisCol StartCol // first decide which way to search IF StartCol = 1 THEN ← Step 1 ← EndCol 1281 ELSE ← Step -1 ← EndCol 0 ENDIF WHILE ThisCol <> EndCol AND Found = FALSE IF Screen[ThisRow, ThisCol] <> 1 THEN ← ThisCol ThisCol + Step ELSE ← Found TRUE ENDIF ENDWHILE IF Found = FALSE THEN ← ThisCol -1 ENDIF RETURN ThisCol ENDFUNCTION Mark as follows: 1 Interpreting parameter to determine direction of search StartCol 2 An attempt at searching both up and down 3 Conditional Loop / Count-controlled loop with use of index ThisCol 4 Using correct values for , and StartCol EndCol Step 5 Reference a element and compare with 1 in a loop Screen 6 If equal save column or immediately Return column in a loop 7 Return column number or −1 Loop(s) terminate when element with value = 1 found Max 7 marks if function heading, including return type, and ending is incorrect or incomplete

6(c)

FUNCTION GetCentreCol(ThisRow : INTEGER) RETURNS INTEGER DECLARE StartCol, EndCol, CentreCol : INTEGER ← StartCol SearchInRow(ThisRow, 1) IF StartCol = -1 THEN ← CentreCol StartCol ELSE ← EndCol SearchInRow(ThisRow, 1280) ← CentreCol INT((StartCol + EndCol)/2) ENDIF RETURN CentreCol ENDFUNCTION Mark as follows: 1 Declaration of local for return value INTEGER 2 Use with correct parameters and check for SearchInRow() -1 3 Use and SearchInRow(ThisRow, 1) SearchInRow(ThisRow, 1280) 4 Calculate centre column 5 Use of function // use of INT() DIV 6 Return –1 or centre value Max 5 marks if function heading, including return type, and ending is incorrect or incomplete

Q3
Oct/Nov 2021 Paper 2 v2

A programmer is writing a program to help manage clubs in a school.

Data will be stored about each student in the school and each student may join up to three clubs.

The data will be held in a record structure of type Student .

The program table. mmer has started to define the fie elds that will be needed as shown in the followi
Field Typical value Comment
StudentID "CF1234" Unique to each student
Email "Carmen47@xyzmail.com" Contains letters, numbers and certain symbols
Club_1 1 Any value in the range 1 to 99 inclusive
Club_2 14 Any value in the range 1 to 99 inclusive
Club_3 27 Any value in the range 1 to 99 inclusive

(a) (i) Write pseudocode to declare the record structure for type Student . 3 marks

(ii) A 1D array Membership containing 3000 elements will be used to store the student data. 2 marks

Write pseudocode to declare the Membership array.

(iii) Some of the elements of the array will be unused. 1 mark

Give an appropriate way of indicating an unused array element.

(iv) Some students are members of less than three clubs. 1 mark

State one way of indicating an unused club field.

(b) A procedure GetIDs() will: 7 marks

  • prompt and input the number of a club

  • output the StudentID of all the students who are members of that club

  • output a count of all students in the given club.

Write pseudocode for the procedure GetIDs() .

A programmer is writing a program to help manage clubs in a school. Data will be stored about each student in the school and each student may join up to three clubs. The data will be held in a record structure of type `Student` . |The program table.|mmer has started to define the fie|elds that will be needed as shown in the followi| |---|---|---| |**Field**|**Typical value**|**Comment**| |`StudentID`|`"CF1234"`|Unique to each student| |`Email`|`"Carmen47@xyzmail.com"`|Contains letters, numbers and certain symbols| |`Club_1`|`1`|Any value in the range 1 to 99 inclusive| |`Club_2`|`14`|Any value in the range 1 to 99 inclusive| |`Club_3`|`27`|Any value in the range 1 to 99 inclusive| **(a) (i)** Write pseudocode to declare the record structure for type `Student` . <span class="part-marks">3 marks</span> #### (ii) A 1D array `Membership` containing 3000 elements will be used to store the student data. <span class="part-marks">2 marks</span> Write pseudocode to declare the `Membership` array. #### (iii) Some of the elements of the array will be unused. <span class="part-marks">1 mark</span> Give an **appropriate** way of indicating an unused array element. #### (iv) Some students are members of less than three clubs. <span class="part-marks">1 mark</span> State **one** way of indicating an unused club field. ### (b) A procedure `GetIDs()` will: <span class="part-marks">7 marks</span> - prompt and input the number of a club - output the `StudentID` of all the students who are members of that club - output a count of all students in the given club. Write pseudocode for the procedure `GetIDs()` .
Show mark scheme

3(a)(i) [2 marks]

Pseudocode: TYPE Student DECLARE StudentID : STRING DECLARE Email : STRING DECLARE Club_1 : INTEGER DECLARE Club_2 : INTEGER DECLARE Club_3 : INTEGER ENDTYPE Mark as follows: One mark for and • TYPE ENDTYPE One mark for and fields as • StudentID Email STRING One mark for all Club fields as • INTEGER

3(a)(ii)

DECLARE Membership : ARRAY [1:3000] OF Student One mark per underlined phrase

3(a)(iii) [1 mark]

One mark for any one of: Assign a value (of the corrrect data type) outside the normal range to one • of the fields Assign an empty string to the field / field • StudentID Email or value out of range to any club field •

3(a)(iv) [7 marks]

A number outside the range 1 to 99

3(b)

PROCEDURE GetIDs() DECLARE Index : INTEGER DECLARE ThisClub, Count : INTEGER OUTPUT "Please Input Club Number: " INPUT ThisClub ← Count 0 ← FOR Index 1 TO 3000 IF Membership[Index].Club_1 = ThisClub OR __ Membership[Index].Club_2 = ThisClub OR __ Membership[Index].Club_3 = ThisClub THEN ← Count Count + 1 OUTPUT Membership[Index].StudentID ENDIF NEXT Index OUTPUT "There are ", Count, " Students in the club" ENDPROCEDURE Mark as follows: 1 Declare and initialise Count 2 Prompt and Input club number before the loop 3 Loop through 3000 elements 4 Compare one club field with number input 5 Compare all fields with number input Club 6 If number found, of field and increment OUTPUT StudentID Count 7 Final of outside the loop OUTPUT Count Note: Max 6 if procedure heading and ending missing or incorrect (but allow array as parameter)

Q6
Oct/Nov 2021 Paper 2 v2

A mobile phone has a touchscreen. The screen is represented by a grid, divided into 800 rows and 1280 columns.

The grid is represented by a 2D array Screen of type INTEGER . An array element will be set to 0 unless the user touches that part of the screen.

Many array elements will set to 1 by a single touch of a finger or a stylus.

The following diagram shows a simplified touchscreen. The dark line represents a touch on the screen. All grid elements that are wholly or partly inside the outline will be set to 1. These elements are shaded. The element shaded in black represents the centre point of the touch.

11

A program is needed to find the coordinates (the row and column) of the centre point. The centre point on the diagram shown is row 6, column 11.

Assume:

  • the user may only touch one area at a time

  • screen rotation does not affect the touchscreen.

The programmer has decided to use global values CentreRow and CentreCol as coordinate values for the centre point.

The programmer has started to define program modules as follows:

Module Description
FirstRowSet() • Searches for the first row that has an array element set to 1
• Returns the index of that row (1 is the first row)
• Returns −1 if there are no elements set to 1
LastRowSet() • Searches for the last row that has an array element set to 1
• Returns the index of that row
• Returns −1 if there are no elements set to 1
FirstColSet() • Searches for the first column that has an array element set to 1
• Returns the index of that column (1 is the first column)
• Returns −1 if there are no elements set to 1
LastColSet() • Searches for the last column that has an array element set to 1
• Returns the index of that column
• Returns −1 if there are no elements set to 1

(a) Write efficient pseudocode for the module FirstRowSet() . 7 marks

(b) Describe a feature of your solution to part (a) that indicates the pseudocode represents an efficient algorithm. 2 marks

(c) The programmer decides to produce a single search module FindSet(), which will be able to perform each of the individual searches performed by the first four modules in the table.

(i) Outline the changes needed to convert one of the existing modules into this single module. 2 marks

(ii) Give one possible advantage and one possible disadvantage of combining the four searches into a single module. 2 marks 6 marks

Advantage

Disadvantage

(d) An additional m module GetCentre() is defined as follows:
Module Description
GetCentre() • Calculates the coordinates of the centre point
• Uses the four modules:FirstRowSet(), LastRowSet(),
FirstColSet(), LastColSet()
• Assigns values toCentreRow andCentreCol
• SetsCentreRow to −1 if no screen touch is detected

Write pseudocode for the module GetCentre() .

A mobile phone has a touchscreen. The screen is represented by a grid, divided into 800 rows and 1280 columns. The grid is represented by a 2D array `Screen` of type `INTEGER` . An array element will be set to 0 unless the user touches that part of the screen. Many array elements will set to 1 by a single touch of a finger or a stylus. The following diagram shows a simplified touchscreen. The dark line represents a touch on the screen. All grid elements that are wholly or partly inside the outline will be set to 1. These elements are shaded. The element shaded in black represents the centre point of the touch. |||||||||||11||||||||||||| |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| |||||||||||||||||||||||| |||||||||||||||||||||||| |||||||||||||||||||||||| |||||||||||||||||||||||| |||||||||||||||||||||||| |||||||||||||||||||||||| |||||||||||||||||||||||| |||||||||||||||||||||||| |||||||||||||||||||||||| |||||||||||||||||||||||| |||||||||||||||||||||||| |||||||||||||||||||||||| |||||||||||||||||||||||| A program is needed to find the coordinates (the row and column) of the centre point. The centre point on the diagram shown is row 6, column 11. Assume: - the user may only touch one area at a time - screen rotation does not affect the touchscreen. The programmer has decided to use global values `CentreRow` and `CentreCol` as coordinate values for the centre point. The programmer has started to define program modules as follows: |Module|Description| |---|---| |`FirstRowSet()`|• Searches for the first row that has an array element set to 1<br>• Returns the index of that row (1 is the first row)<br>• Returns −1 if there are no elements set to 1| |`LastRowSet()`|• Searches for the last row that has an array element set to 1<br>• Returns the index of that row<br>• Returns −1 if there are no elements set to 1| |`FirstColSet()`|• Searches for the first column that has an array element set to 1<br>• Returns the index of that column (1 is the first column)<br>• Returns −1 if there are no elements set to 1| |`LastColSet()`|• Searches for the last column that has an array element set to 1<br>• Returns the index of that column<br>• Returns −1 if there are no elements set to 1| ### (a) Write efficient pseudocode for the module `FirstRowSet()` . <span class="part-marks">7 marks</span> ### (b) Describe a feature of your solution to **part (a)** that indicates the pseudocode represents an efficient algorithm. <span class="part-marks">2 marks</span> ### (c) The programmer decides to produce a **single** search module `FindSet()`, which will be able to perform each of the individual searches performed by the first four modules in the table. #### (i) Outline the changes needed to convert one of the existing modules into this single module. <span class="part-marks">2 marks</span> #### (ii) Give one possible advantage **and** one possible disadvantage of combining the four searches into a single module. <span class="part-marks">2 marks</span> <span class="part-marks">6 marks</span> Advantage Disadvantage |(d) An additional m|module GetCentre() is defined as follows:| |---|---| |**Module**|**Description**| |`GetCentre()`|• Calculates the coordinates of the centre point<br>• Uses the four modules:`FirstRowSet()`, `LastRowSet()`, <br>`FirstColSet()`, `LastColSet()`<br>• Assigns values to`CentreRow` and`CentreCol`<br>• Sets`CentreRow` to −1 if no screen touch is detected| Write pseudocode for the module `GetCentre()` .
Show mark scheme

6(a)

FUNCTION FirstRowSet() RETURNS INTEGER DECLARE Row, Col : INTEGER DECLARE Found : BOOLEAN // array is 1280 × 800 ← Row 1 ← Found FALSE WHILE Row <= 800 AND Found = FALSE // top to bottom ← Col 1 WHILE Col <= 1280 AND Found = FALSE // left to right IF Screen[Row,Col] = 1 THEN ← Found TRUE // end function as soon as first // found ENDIF ← Col Col + 1 ENDWHILE ← Row Row + 1 ENDWHILE IF Found = FALSE THEN // nothing found ← Row 0 ENDIF RETURN Row - 1 ENDFUNCTION Mark as follows: 1 Function heading and ending and return type 2 (Conditional) outer loop 1 to 800 (row) 3 (Conditional) inner loop 1 to 1280 // 1280 to 1 (column) 4 Reference element and test for = 1 // <> 0 Screen 5 and if true save row number and exit loops 6 Increment index variables in both inner and outer loop 7 Return Row number or −1, following a reasonable attempt

6(b) [2 marks]

One mark for: (A flag is used to) exit the loops // iteration is terminated • as soon as a Screen element with value 1 is found •

6(c)(i) [2 marks]

One mark for: Parameter(s) need to be passed to the module to identify the type of • search Search algorithm is controlled by (global) variables / parameters • Alternative: The search algorithms from the original modules are included in the new • module The new module needs to return / store the four values (the results of the • four searches)

6(c)(ii) [6 marks]

One mark for advantage and one for disadvantage: Advantage: (max 1) Only have to change one module if specification changes • Less repetitive code / fewer lines of code • Aids re-usability • Disadvantage: (max 1) Single module more complex / more error prone / more difficult to • debug ... Single module cannot be split among programmers / teams • Max 2

6(d)

PROCEDURE GetCentre () DECLARE StartRow, EndRow, StartCol, EndCol : INTEGER ← StartRow FirstRowSet() IF StartRow = -1 THEN ← CentreRow -1 // no 'touch' detected ELSE ← EndRow LastRowSet() ← StartCol FirstColSet() ← EndCol LastColSet() ← CentreRow INT((StartRow + EndRow)/2) ← CentreCol INT((StartCol + EndCol)/2) ENDIF ENDPROCEDURE Mark as follows: 1 Call and check for -1 // check for no element set Set 2 ...and if so set to –1 CentreRow 3 Call all 4 functions to get 'extremity' values Set 4 Calculate centre row and centre column 5 Use of function or operator on values from MP4 INT() DIV 6 Assign calculated values to and CentreRow CentreCol Note: Max 5 if procedure heading and ending missing or incorrect (ignore array if passed as a parameter) or any local variables are undefined or of incorrect type

Q6
Oct/Nov 2021 Paper 2 v3

A mobile phone has a touchscreen. The screen is represented by a grid, divided into 800 rows and 1280 columns.

The grid is represented by a 2D array Screen of type INTEGER . An array element will be set to 0 unless the user touches that part of the screen.

Many array elements are set to 1 by a single touch of a finger or a stylus.

The following diagram shows a simplified touchscreen. The dark line represents a touch to the screen. All grid elements that are wholly or partly inside the outline will be set to 1. These elements are shaded. The element shaded in black represents the centre point.

11

A program is needed to find the coordinates (the row and column) of the centre point. The centre point on the diagram above is row 6, column 11.

Assume:

  • the user may only touch one area at a time

  • screen rotation does not affect the touchscreen.

The programmer has started to define program modules as follows:

Module Description
SetRow()
(generates test
data)
• Called with three parameters of typeINTEGER:
◦a row number
◦the number of pixels to be skipped starting from column 1
◦the number of pixels that should be set to 1
• Sets the required number of pixels to 1
For example,SetRow(3, 8, 5) will give row 3 as in the diagram shown.
SearchInRow()
• Takes two parameters of typeINTEGER:
◦a row number
◦a start column (1 or 1280)
• Searches the given row from the start column (either left to right or right to left)
for the first column that contains an element set to 1
• Returns the column number of the first element in the given row that is set to 1
• Returns −1 if no element is set to 1
SearchInCol() • Takes two parameters of typeINTEGER:
◦a column number
◦a start row (1 or 800)
• Searches the given column from the start row (either up or down) for the first
row that contains an element set to 1
• Returns the row number of the first element in the given column that is set to 1
• Returns −1 if no element is set to 1

(a) Write pseudocode to implement the module SetRow() . 5 marks 8 marks 6 marks

(b) The modul le description of SearchInRow() is provided here for reference.
Module Description
SearchInRow() • Takes two parameters of typeINTEGER:
◦a row number
◦a start column (1 or 1280)
• Searches the given row from the start column (either left to right or right to left)
for the first column that contains an element set to 1
• Returns the column number of the first element in the given row that is set to 1
• Returns −1 if no element is set to 1

Write pseudocode to implement the module SearchInRow() .

(c) The followi ing new module is introduced:
Module Description
GetCentreCol() • Called with a row number as anINTEGER
• UsesSearchInRow() to find the first and last columns in the given row which
have an array element set to 1
• Returns the index of the column midway between the first and last columns
• Returns −1 if no element is set to 1

Write pseudocode to implement the module GetCentreCol() .

A mobile phone has a touchscreen. The screen is represented by a grid, divided into 800 rows and 1280 columns. The grid is represented by a 2D array `Screen` of type `INTEGER` . An array element will be set to 0 unless the user touches that part of the screen. Many array elements are set to 1 by a single touch of a finger or a stylus. The following diagram shows a simplified touchscreen. The dark line represents a touch to the screen. All grid elements that are wholly or partly inside the outline will be set to 1. These elements are shaded. The element shaded in black represents the centre point. |||||||||||11|||||||||||||| |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| ||||||||||||||||||||||||| A program is needed to find the coordinates (the row and column) of the centre point. The centre point on the diagram above is row 6, column 11. Assume: - the user may only touch one area at a time - screen rotation does not affect the touchscreen. The programmer has started to define program modules as follows: |Module|Description| |---|---| |`SetRow()`<br>(generates test<br>data)|• Called with three parameters of type`INTEGER`:<br> ◦a row number<br> ◦the number of pixels to be skipped starting from column 1<br> ◦the number of pixels that should be set to 1<br>• Sets the required number of pixels to 1<br>For example,`SetRow(3, 8, 5)` will give row 3 as in the diagram shown.| |`SearchInRow()`|<br>• Takes two parameters of type`INTEGER`:<br> ◦a row number<br> ◦a start column (1 or 1280)<br>• Searches the given row from the start column (either left to right or right to left)<br>for the first column that contains an element set to 1<br>• Returns the column number of the first element in the given row that is set to 1<br>• Returns −1 if no element is set to 1| |`SearchInCol()`|• Takes two parameters of type`INTEGER`:<br> ◦a column number<br> ◦a start row (1 or 800)<br>• Searches the given column from the start row (either up or down) for the first<br>row that contains an element set to 1<br>• Returns the row number of the first element in the given column that is set to 1<br>• Returns −1 if no element is set to 1| ### (a) Write pseudocode to implement the module `SetRow()` . <span class="part-marks">5 marks</span> <span class="part-marks">8 marks</span> <span class="part-marks">6 marks</span> |(b) The modul|le description of SearchInRow() is provided here for reference.| |---|---| |**Module**|**Description**| |`SearchInRow()`|• Takes two parameters of type`INTEGER`:<br> ◦a row number<br> ◦a start column (1 or 1280)<br>• Searches the given row from the start column (either left to right or right to left)<br>for the first column that contains an element set to 1<br>• Returns the column number of the first element in the given row that is set to 1<br>• Returns −1 if no element is set to 1| Write pseudocode to implement the module `SearchInRow()` . |(c) The followi|ing new module is introduced:| |---|---| |**Module**|**Description**| |`GetCentreCol()`|• Called with a row number as an`INTEGER`<br>• Uses`SearchInRow()` to find the first and last columns in the given row which<br>have an array element set to 1<br>• Returns the index of the column midway between the first and last columns<br>• Returns −1 if no element is set to 1| Write pseudocode to implement the module `GetCentreCol()` .
Show mark scheme

6(a) [8 marks]

PROCEDURE SetRow(Row, SkipNum, SetNum : INTEGER) DECLARE Col : INTEGER // array is 1280 x 800 ← FOR Col SkipNum + 1 TO SkipNum + SetNum ← Screen[Row, Col] 1 NEXT Index ENDPROCEDURE ALTERNATIVE 1: ← FOR Col 1 TO SetNum ← Screen[Row, SkipNum + Col] 1 NEXT Col ALTERNATIVE 2: WHILE SetNum > 0 ← Screen[Row, SkipNum + SetNum] 1 ← SetNum SetNum - 1 ENDWHILE Mark as follows: 1 Procedure heading and ending including parameters 2 Declaration of local Integer for Col 3 Count-controlled loop with meaningful start number 4 correct stop number 5 Reference Screen Array element and set to 1 in a loop

6(b) [6 marks]

FUNCTION SearchInRow(ThisRow, StartCol : INTEGER) RETURNS INTEGER DECLARE ThisCol, Step : INTEGER DECLARE Found: BOOLEAN // array is 1280 x 800 ← Found FALSE ← ThisCol StartCol // first decide which way to search IF StartCol = 1 THEN ← Step 1 ← EndCol 1281 ELSE ← Step -1 ← EndCol 0 ENDIF WHILE ThisCol <> EndCol AND Found = FALSE IF Screen[ThisRow, ThisCol] <> 1 THEN ← ThisCol ThisCol + Step ELSE ← Found TRUE ENDIF ENDWHILE IF Found = FALSE THEN ← ThisCol -1 ENDIF RETURN ThisCol ENDFUNCTION Mark as follows: 1 Interpreting parameter to determine direction of search StartCol 2 An attempt at searching both up and down 3 Conditional Loop / Count-controlled loop with use of index ThisCol 4 Using correct values for , and StartCol EndCol Step 5 Reference a element and compare with 1 in a loop Screen 6 If equal save column or immediately Return column in a loop 7 Return column number or −1 Loop(s) terminate when element with value = 1 found Max 7 marks if function heading, including return type, and ending is incorrect or incomplete

6(c)

FUNCTION GetCentreCol(ThisRow : INTEGER) RETURNS INTEGER DECLARE StartCol, EndCol, CentreCol : INTEGER ← StartCol SearchInRow(ThisRow, 1) IF StartCol = -1 THEN ← CentreCol StartCol ELSE ← EndCol SearchInRow(ThisRow, 1280) ← CentreCol INT((StartCol + EndCol)/2) ENDIF RETURN CentreCol ENDFUNCTION Mark as follows: 1 Declaration of local for return value INTEGER 2 Use with correct parameters and check for SearchInRow() -1 3 Use and SearchInRow(ThisRow, 1) SearchInRow(ThisRow, 1280) 4 Calculate centre column 5 Use of function // use of INT() DIV 6 Return –1 or centre value Max 5 marks if function heading, including return type, and ending is incorrect or incomplete

Q5
May/Jun 2021 Paper 2 v1

A global 2D array Result of type INTEGER is used to store a list of exam candidate numbers together with their marks. The array contains 2000 elements, organised as 1000 rows and 2 columns.

Column 1 contains the candidate number and column 2 contains the mark for the corresponding candidate. All elements contain valid exam result data.

A procedure Sort() is needed to sort Result into ascending order of mark using an efficient bubble sort algorithm.

Write pseudocode for the procedure Sort() . 8 marks

A global 2D array `Result` of type `INTEGER` is used to store a list of exam candidate numbers together with their marks. The array contains 2000 elements, organised as 1000 rows and 2 columns. Column 1 contains the candidate number and column 2 contains the mark for the corresponding candidate. All elements contain valid exam result data. A procedure `Sort()` is needed to sort `Result` into ascending order of mark using an efficient bubble sort algorithm. Write pseudocode for the procedure `Sort()` . <span class="part-marks">8 marks</span>
Show mark scheme

5 [4 marks]

PROCEDURE Sort() DECLARE Temp : INTEGER DECLARE NoSwaps : BOOLEAN DECLARE Boundary, Row, Col : INTEGER ← Boundary 999 REPEAT ← NoSwaps TRUE ← FOR Row 1 TO Boundary IF Result[Row, 2] > Result[Row + 1, 2] THEN ← FOR Col 1 TO 2 ← Temp Result [Row, Col] ← Result [Row, Col] Result [Row + 1, Col] ← Result [Row + 1, Col] Temp NEXT Col ← NoSwaps FALSE ENDIF NEXT J ← Boundary Boundary - 1 UNTIL NoSwaps = TRUE ENDPROCEDURE Mark as follows: 1 Outer loop 2 Inner loop 3 Correct comparison in a loop 4 Correct swap of col1 array elements in a loop 5 Correct swap of col2 array elements in a loop (via loop or separate statements) 6 mechanism: Conditional outer loop including flag reset 'NoSwap' 7 mechanism: Set flag in inner loop to indicate swap 'NoSwap' 8 Reducing Boundary in the outer loop

Q5
May/Jun 2021 Paper 2 v2

(a) A student is learning about arrays.

She wants to write a program to:

  • declare a 1D array RNum of 100 elements of type INTEGER

  • assign each element a random value in the range 1 to 200 inclusive

  • count and output how many numbers generated were between 66 and 173 inclusive.

(i) Write pseudocode to represent the algorithm. 6 marks

(ii) The student decides to modify the algorithm so that each element of the array will contain a unique value. 3 marks

Describe the changes that the student needs to make to the algorithm.

### (a) A student is learning about arrays. She wants to write a program to: - declare a 1D array `RNum` of 100 elements of type `INTEGER` - assign each element a random value in the range 1 to 200 inclusive - count and output how many numbers generated were between 66 and 173 inclusive. #### (i) Write pseudocode to represent the algorithm. <span class="part-marks">6 marks</span> #### (ii) The student decides to modify the algorithm so that each element of the array will contain a unique value. <span class="part-marks">3 marks</span> Describe the changes that the student needs to make to the algorithm.
Show mark scheme

5(a)(i)

DECLARE RNum : ARRAY[1:100] OF INTEGER DECLARE Index, Count : INTEGER ← Count 0 ← FOR Index 1 TO 100 ← RNum[Index] INT(RAND(200)) + 1 IF RNum[Index] >= 66 AND RNum[Index] <= 173 THEN ← Count Count + 1 ENDIF NEXT Index OUTPUT Count Mark as follows: 1 Array declaration 2 Loop for 100 iterations 3 Array element index 'syntax' (left-hand side of assignment expression) in a loop 4 Use of to generate value in range (and assign to array RAND() element) in a loop 5 Check if random number within range and if so, increment count in a loop 6 Output of count (following a reasonable attempt) after the loop

5(a)(ii) [4 marks]

One mark per bullet / sub-bullet point 1 Initialise the array to a rogue value (to indicate 'unassigned' element) 2 Add a conditional loop to: 3 Generate and store a random number (in the correct range) 4 Check the stored number against values already in the array 5 If the stored number is found then generate another random value 6 Otherwise add it to the array (and exit loop) Note: Max 3 marks

5(b)(i) [2 marks]

Give a line number containing an example of an 07 initialisation statement. Give a line number containing the start of a repeating 09 / 10 block of code. Give a line number containing a logic statement. 12 3 Give the number of parameters of function . MID() One mark for each row

5(b)(ii) [8 marks]

IF (NextChar >= 'a') AND (NextChar <= 'z') THEN One mark for IF ... AND ... One mark for both conditions

Q5
May/Jun 2021 Paper 2 v3

A global 2D array Result of type INTEGER is used to store a list of exam candidate numbers together with their marks. The array contains 2000 elements, organised as 1000 rows and 2 columns.

Column 1 contains the candidate number and column 2 contains the mark for the corresponding candidate. All elements contain valid exam result data.

A procedure Sort() is needed to sort Result into ascending order of mark using an efficient bubble sort algorithm.

Write pseudocode for the procedure Sort() . 8 marks

A global 2D array `Result` of type `INTEGER` is used to store a list of exam candidate numbers together with their marks. The array contains 2000 elements, organised as 1000 rows and 2 columns. Column 1 contains the candidate number and column 2 contains the mark for the corresponding candidate. All elements contain valid exam result data. A procedure `Sort()` is needed to sort `Result` into ascending order of mark using an efficient bubble sort algorithm. Write pseudocode for the procedure `Sort()` . <span class="part-marks">8 marks</span>
Show mark scheme

5 [4 marks]

PROCEDURE Sort() DECLARE Temp : INTEGER DECLARE NoSwaps : BOOLEAN DECLARE Boundary, Row, Col : INTEGER ← Boundary 999 REPEAT ← NoSwaps TRUE ← FOR Row 1 TO Boundary IF Result[Row, 2] > Result[Row + 1, 2] THEN ← FOR Col 1 TO 2 ← Temp Result [Row, Col] ← Result [Row, Col] Result [Row + 1, Col] ← Result [Row + 1, Col] Temp NEXT Col ← NoSwaps FALSE ENDIF NEXT J ← Boundary Boundary - 1 UNTIL NoSwaps = TRUE ENDPROCEDURE Mark as follows: 1 Outer loop 2 Inner loop 3 Correct comparison in a loop 4 Correct swap of col1 array elements in a loop 5 Correct swap of col2 array elements in a loop (via loop or separate statements) 6 mechanism: Conditional outer loop including flag reset 'NoSwap' 7 mechanism: Set flag in inner loop to indicate swap 'NoSwap' 8 Reducing Boundary in the outer loop

Q2
May/Jun 2021 Paper 4 v1

A program stores the following ten integers in a 1D array with the identifier arrayData .

10 5 6 7 1 12 13 15 21 8

(a) Write program code for a new program to: 2 marks

  • declare the global 1D array, arrayData, with ten elements

  • initialise arrayData in the main program using the data values shown.

Save your program as question2 .

Copy and paste the program code into part 2(a) in the evidence document. (b) (i) A function, linearSearch(), takes an integer as a parameter and performs a linear 6 marks search on arrayData to find the parameter value. It returns True if it was found and False if it was not found.

Write program code for the function linearSearch() .

Save your program.

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

(ii) Edit the main program to: 4 marks

  • allow the user to input an integer value

  • pass the value to linearSearch() as the parameter

  • output an appropriate message to tell the user whether the search value was found or not.

Save your program.

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

(iii) Test your program with one value that is in the array and one value that is not in the array. 2 marks

Take a screenshot to show the result of each test.

Save your program.

Copy and paste the screenshots into part 2(b)(iii) in the evidence document.

(c) The following bubble sort pseudocode algorithm sorts the data in theArray into descending numerical order. There are five incomplete statements. 6 marks

    PROCEDURE bubbleSort()
    DECLARE temp : INTEGER
    FOR x  0 to …………………………………
    FOR y  0 to …………………………………
    IF theArray[y] ………………………………… theArray[y + 1] THEN
    temp  theArray[y]
    theArray[y]  …………………………………
    theArray[y + 1]  …………………………………
    ENDIF
    NEXT y
    NEXT x
    ENDPROCEDURE

Write program code for the procedure bubbleSort() to sort the data in arrayData into descending order.

Save your program.

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

A program stores the following ten integers in a 1D array with the identifier `arrayData` . 10 5 6 7 1 12 13 15 21 8 ### (a) Write program code for a **new program** to: <span class="part-marks">2 marks</span> - declare the global 1D array, `arrayData`, with ten elements - initialise `arrayData` in the main program using the data values shown. Save your program as **question2** . Copy and paste the program code into **part 2(a)** in the evidence document. **(b) (i)** A function, `linearSearch()`, takes an integer as a parameter and performs a linear <span class="part-marks">6 marks</span> search on `arrayData` to find the parameter value. It returns `True` if it was found and `False` if it was not found. Write program code for the function `linearSearch()` . Save your program. Copy and paste the program code into **part 2(b)(i)** in the evidence document. #### (ii) Edit the main program to: <span class="part-marks">4 marks</span> - allow the user to input an integer value - pass the value to `linearSearch()` as the parameter - output an appropriate message to tell the user whether the search value was found or not. Save your program. Copy and paste the program code into **part 2(b)(ii)** in the evidence document. #### (iii) Test your program with one value that is in the array and one value that is not in the array. <span class="part-marks">2 marks</span> Take a screenshot to show the result of each test. Save your program. Copy and paste the screenshots into **part 2(b)(iii)** in the evidence document. ### (c) The following bubble sort pseudocode algorithm sorts the data in `theArray` into descending numerical order. There are **five** incomplete statements. <span class="part-marks">6 marks</span> ``` PROCEDURE bubbleSort() DECLARE temp : INTEGER FOR x 0 to ………………………………… FOR y 0 to ………………………………… IF theArray[y] ………………………………… theArray[y + 1] THEN temp theArray[y] theArray[y] ………………………………… theArray[y + 1] ………………………………… ENDIF NEXT y NEXT x ENDPROCEDURE ``` Write program code for the procedure `bubbleSort()` to sort the data in `arrayData` into descending order. Save your program. Copy and paste the program code into **part 2(c)** in the evidence document.
Show mark scheme

2(a)

arrayData[7] = 15; arrayData[8] = 21; arrayData[9] = 8;

2(b)(i)

Python def linearSearch(searchValue): for x in range(0, 10): if arrayData[x] == searchValue: return True return False public static Boolean linearSearch(Integer searchValue){ for (int x = 0; x < 10; x++){ if(arrayData[x] == searchValue){ return true; } return false;

2(b)(ii)

Python arrayData = [10, 5, 6, 7, 1, 12, 13, 15, 21, 8] searchValue = int(input("Enter the number to search for")) returnValue = linearSearch(searchValue) if returnValue == True: print("It was found") else: print("It was not found") Integer[] arrayData = new Integer[10]; public static void main(String[] args){ arrayData[0] = 10; arrayData[1] = 5; arrayData[2] = 6; arrayData[3] = 7; arrayData[4] = 1; arrayData[5] = 12; arrayData[6] = 13; arrayData[7] = 15; arrayData[8] = 12; arrayData[9] = 8; System.out.println("Enter the number to search for"); Integer searchValue; Scanner in = new Scanner(System.in); searchValue = in.nextInt(); Boolean returnValue; returnValue = linearSearch(searchValue); if (returnValue == true){ System.out.println("It was found"); }else{ System.out.println("It was not found"); }

2(b)(iii) [2 marks]

1 mark for screenshot showing input and output for number found 1 mark for screenshot showing input and output for number not found

2(c)

Python def bubbleSort(): for x in range (0, 10 ): for y in range(0, 9 ): if theArray[y] < theArray[y + 1]: temp = theArray[y] theArray[y] = theArray[y + 1] theArray[y + 1] = temp public static void bubbleSort(){ int temp; for (int x = 0; x < 10 ; x++){ for (int y = 0; y < 9 ; y++){ if(theArray[y] < theArray[y+1]){ temp = theArray[y]; theArray[y] = theArray[y+1] ; theArray[y+1] = temp ; } } }

Q2
May/Jun 2021 Paper 4 v2

A program stores the following ten integers in a 1D array with the identifier arrayData .

10 5 6 7 1 12 13 15 21 8

(a) Write program code for a new program to: 2 marks

  • declare the global 1D array, arrayData, with ten elements

  • initialise arrayData in the main program using the data values shown.

Save your program as question2 .

Copy and paste the program code into part 2(a) in the evidence document. (b) (i) A function, linearSearch(), takes an integer as a parameter and performs a linear 6 marks search on arrayData to find the parameter value. It returns True if it was found and False if it was not found.

Write program code for the function linearSearch() .

Save your program.

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

(ii) Edit the main program to: 4 marks

  • allow the user to input an integer value

  • pass the value to linearSearch() as the parameter

  • output an appropriate message to tell the user whether the search value was found or not.

Save your program.

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

(iii) Test your program with one value that is in the array and one value that is not in the array. 2 marks

Take a screenshot to show the result of each test.

Save your program.

Copy and paste the screenshots into part 2(b)(iii) in the evidence document.

(c) The following bubble sort pseudocode algorithm sorts the data in theArray into descending numerical order. There are five incomplete statements. 6 marks

    PROCEDURE bubbleSort()
    DECLARE temp : INTEGER
    FOR x  0 to …………………………………
    FOR y  0 to …………………………………
    IF theArray[y] ………………………………… theArray[y + 1] THEN
    temp  theArray[y]
    theArray[y]  …………………………………
    theArray[y + 1]  …………………………………
    ENDIF
    NEXT y
    NEXT x
    ENDPROCEDURE

Write program code for the procedure bubbleSort() to sort the data in arrayData into descending order.

Save your program.

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

A program stores the following ten integers in a 1D array with the identifier `arrayData` . 10 5 6 7 1 12 13 15 21 8 ### (a) Write program code for a **new program** to: <span class="part-marks">2 marks</span> - declare the global 1D array, `arrayData`, with ten elements - initialise `arrayData` in the main program using the data values shown. Save your program as **question2** . Copy and paste the program code into **part 2(a)** in the evidence document. **(b) (i)** A function, `linearSearch()`, takes an integer as a parameter and performs a linear <span class="part-marks">6 marks</span> search on `arrayData` to find the parameter value. It returns `True` if it was found and `False` if it was not found. Write program code for the function `linearSearch()` . Save your program. Copy and paste the program code into **part 2(b)(i)** in the evidence document. #### (ii) Edit the main program to: <span class="part-marks">4 marks</span> - allow the user to input an integer value - pass the value to `linearSearch()` as the parameter - output an appropriate message to tell the user whether the search value was found or not. Save your program. Copy and paste the program code into **part 2(b)(ii)** in the evidence document. #### (iii) Test your program with one value that is in the array and one value that is not in the array. <span class="part-marks">2 marks</span> Take a screenshot to show the result of each test. Save your program. Copy and paste the screenshots into **part 2(b)(iii)** in the evidence document. ### (c) The following bubble sort pseudocode algorithm sorts the data in `theArray` into descending numerical order. There are **five** incomplete statements. <span class="part-marks">6 marks</span> ``` PROCEDURE bubbleSort() DECLARE temp : INTEGER FOR x 0 to ………………………………… FOR y 0 to ………………………………… IF theArray[y] ………………………………… theArray[y + 1] THEN temp theArray[y] theArray[y] ………………………………… theArray[y + 1] ………………………………… ENDIF NEXT y NEXT x ENDPROCEDURE ``` Write program code for the procedure `bubbleSort()` to sort the data in `arrayData` into descending order. Save your program. Copy and paste the program code into **part 2(c)** in the evidence document.
Show mark scheme

2(a)

arrayData[7] = 15; arrayData[8] = 21; arrayData[9] = 8;

2(b)(i)

Python def linearSearch(searchValue): for x in range(0, 10): if arrayData[x] == searchValue: return True return False public static Boolean linearSearch(Integer searchValue){ for (int x = 0; x < 10; x++){ if(arrayData[x] == searchValue){ return true; } return false;

2(b)(ii)

Python arrayData = [10, 5, 6, 7, 1, 12, 13, 15, 21, 8] searchValue = int(input("Enter the number to search for")) returnValue = linearSearch(searchValue) if returnValue == True: print("It was found") else: print("It was not found") Integer[] arrayData = new Integer[10]; public static void main(String[] args){ arrayData[0] = 10; arrayData[1] = 5; arrayData[2] = 6; arrayData[3] = 7; arrayData[4] = 1; arrayData[5] = 12; arrayData[6] = 13; arrayData[7] = 15; arrayData[8] = 12; arrayData[9] = 8; System.out.println("Enter the number to search for"); Integer searchValue; Scanner in = new Scanner(System.in); searchValue = in.nextInt(); Boolean returnValue; returnValue = linearSearch(searchValue); if (returnValue == true){ System.out.println("It was found"); }else{ System.out.println("It was not found"); }

2(b)(iii) [2 marks]

1 mark for screenshot showing input and output for number found 1 mark for screenshot showing input and output for number not found

2(c)

Python def bubbleSort(): for x in range (0, 10 ): for y in range(0, 9 ): if theArray[y] < theArray[y + 1]: temp = theArray[y] theArray[y] = theArray[y + 1] theArray[y + 1] = temp public static void bubbleSort(){ int temp; for (int x = 0; x < 10 ; x++){ for (int y = 0; y < 9 ; y++){ if(theArray[y] < theArray[y+1]){ temp = theArray[y]; theArray[y] = theArray[y+1] ; theArray[y+1] = temp ; } } }

Q2
May/Jun 2021 Paper 4 v3

A program stores the following ten integers in a 1D array with the identifier arrayData .

10 5 6 7 1 12 13 15 21 8

(a) Write program code for a new program to: 2 marks

  • declare the global 1D array, arrayData, with ten elements

  • initialise arrayData in the main program using the data values shown.

Save your program as question2 .

Copy and paste the program code into part 2(a) in the evidence document. (b) (i) A function, linearSearch(), takes an integer as a parameter and performs a linear 6 marks search on arrayData to find the parameter value. It returns True if it was found and False if it was not found.

Write program code for the function linearSearch() .

Save your program.

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

(ii) Edit the main program to: 4 marks

  • allow the user to input an integer value

  • pass the value to linearSearch() as the parameter

  • output an appropriate message to tell the user whether the search value was found or not.

Save your program.

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

(iii) Test your program with one value that is in the array and one value that is not in the array. 2 marks

Take a screenshot to show the result of each test.

Save your program.

Copy and paste the screenshots into part 2(b)(iii) in the evidence document.

(c) The following bubble sort pseudocode algorithm sorts the data in theArray into descending numerical order. There are five incomplete statements. 6 marks

    PROCEDURE bubbleSort()
    DECLARE temp : INTEGER
    FOR x  0 to …………………………………
    FOR y  0 to …………………………………
    IF theArray[y] ………………………………… theArray[y + 1] THEN
    temp  theArray[y]
    theArray[y]  …………………………………
    theArray[y + 1]  …………………………………
    ENDIF
    NEXT y
    NEXT x
    ENDPROCEDURE

Write program code for the procedure bubbleSort() to sort the data in arrayData into descending order.

Save your program.

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

A program stores the following ten integers in a 1D array with the identifier `arrayData` . 10 5 6 7 1 12 13 15 21 8 ### (a) Write program code for a **new program** to: <span class="part-marks">2 marks</span> - declare the global 1D array, `arrayData`, with ten elements - initialise `arrayData` in the main program using the data values shown. Save your program as **question2** . Copy and paste the program code into **part 2(a)** in the evidence document. **(b) (i)** A function, `linearSearch()`, takes an integer as a parameter and performs a linear <span class="part-marks">6 marks</span> search on `arrayData` to find the parameter value. It returns `True` if it was found and `False` if it was not found. Write program code for the function `linearSearch()` . Save your program. Copy and paste the program code into **part 2(b)(i)** in the evidence document. #### (ii) Edit the main program to: <span class="part-marks">4 marks</span> - allow the user to input an integer value - pass the value to `linearSearch()` as the parameter - output an appropriate message to tell the user whether the search value was found or not. Save your program. Copy and paste the program code into **part 2(b)(ii)** in the evidence document. #### (iii) Test your program with one value that is in the array and one value that is not in the array. <span class="part-marks">2 marks</span> Take a screenshot to show the result of each test. Save your program. Copy and paste the screenshots into **part 2(b)(iii)** in the evidence document. ### (c) The following bubble sort pseudocode algorithm sorts the data in `theArray` into descending numerical order. There are **five** incomplete statements. <span class="part-marks">6 marks</span> ``` PROCEDURE bubbleSort() DECLARE temp : INTEGER FOR x 0 to ………………………………… FOR y 0 to ………………………………… IF theArray[y] ………………………………… theArray[y + 1] THEN temp theArray[y] theArray[y] ………………………………… theArray[y + 1] ………………………………… ENDIF NEXT y NEXT x ENDPROCEDURE ``` Write program code for the procedure `bubbleSort()` to sort the data in `arrayData` into descending order. Save your program. Copy and paste the program code into **part 2(c)** in the evidence document.
Show mark scheme

2(a)

arrayData[7] = 15; arrayData[8] = 21; arrayData[9] = 8;

2(b)(i)

Python def linearSearch(searchValue): for x in range(0, 10): if arrayData[x] == searchValue: return True return False public static Boolean linearSearch(Integer searchValue){ for (int x = 0; x < 10; x++){ if(arrayData[x] == searchValue){ return true; } return false;

2(b)(ii)

Python arrayData = [10, 5, 6, 7, 1, 12, 13, 15, 21, 8] searchValue = int(input("Enter the number to search for")) returnValue = linearSearch(searchValue) if returnValue == True: print("It was found") else: print("It was not found") Integer[] arrayData = new Integer[10]; public static void main(String[] args){ arrayData[0] = 10; arrayData[1] = 5; arrayData[2] = 6; arrayData[3] = 7; arrayData[4] = 1; arrayData[5] = 12; arrayData[6] = 13; arrayData[7] = 15; arrayData[8] = 12; arrayData[9] = 8; System.out.println("Enter the number to search for"); Integer searchValue; Scanner in = new Scanner(System.in); searchValue = in.nextInt(); Boolean returnValue; returnValue = linearSearch(searchValue); if (returnValue == true){ System.out.println("It was found"); }else{ System.out.println("It was not found"); }

2(b)(iii) [2 marks]

1 mark for screenshot showing input and output for number found 1 mark for screenshot showing input and output for number not found

2(c)

Python def bubbleSort(): for x in range (0, 10 ): for y in range(0, 9 ): if theArray[y] < theArray[y + 1]: temp = theArray[y] theArray[y] = theArray[y + 1] theArray[y + 1] = temp public static void bubbleSort(){ int temp; for (int x = 0; x < 10 ; x++){ for (int y = 0; y < 9 ; y++){ if(theArray[y] < theArray[y+1]){ temp = theArray[y]; theArray[y] = theArray[y+1] ; theArray[y+1] = temp ; } } }