Skip to content

11.3 Structured Programming

AS Level · 42 questions found

  • Define and use procedures; pass parameters by value or by reference
  • Define and use functions; return values used in expressions
  • Terminology: header, interface, parameter, argument, return value
  • Write efficient pseudocode
Q1
Oct/Nov 2025 Paper 2 v3

A user requires a program that implements complex data encryption to a recognised international standard. A programmer has started the design of the program.

(a) The programmer decides to use a library routine to provide part of the solution. One reason for this is that library routines may perform functions that the programmer is unable to program themselves. 3 marks

State three other benefits of using library routines in the development of the program.

1

2

3

(b) The programmer has identified a different part of the algorithm that would be appropriate to implement as a subroutine (a procedure or a function); no suitable library routine exists for this part.

(i) State two reasons why the programmer may decide to use a subroutine. 2 marks

1

2

(ii) A function header in pseudocode is defined as: 2 marks

FUNCTION Pass2(Count : INTEGER) RETURNS BOOLEAN

Complete the table by describing the terms used in the function header.

The first row has been completed.

Term Description
Pass2 the name of the function
Count
BOOLEAN

(c) Variables in the program have example values: 3 marks

Variable Example value
DoB 23/6/2011
Multiplier 2.5
AddressLine[1] "35 Lincoln Avenue"

Complete the table by evaluating each expression using the example values:

Expression Evaluates to
LENGTH(NUM_TO_STR(Multiplier))
MONTH(DoB) > 4
15 + STR_TO_NUM(MID(AddressLine[1], 2, 1))
A user requires a program that implements complex data encryption to a recognised international standard. A programmer has started the design of the program. ### (a) The programmer decides to use a library routine to provide part of the solution. One reason for this is that library routines may perform functions that the programmer is unable to program themselves. <span class="part-marks">3 marks</span> State three other benefits of using library routines in the development of the program. 1 2 3 ### (b) The programmer has identified a different part of the algorithm that would be appropriate to implement as a subroutine (a procedure or a function); no suitable library routine exists for this part. #### (i) State two reasons why the programmer may decide to use a subroutine. <span class="part-marks">2 marks</span> 1 2 #### (ii) A function header in pseudocode is defined as: <span class="part-marks">2 marks</span> FUNCTION Pass2(Count : INTEGER) RETURNS BOOLEAN Complete the table by describing the terms used in the function header. The first row has been completed. |Term|Description| |---|---| |Pass2|the name of the function| |Count|| |BOOLEAN|| ### (c) Variables in the program have example values: <span class="part-marks">3 marks</span> |Variable|Example value| |---|---| |DoB|23/6/2011| |Multiplier|2.5| |AddressLine[1]|"35 Lincoln Avenue"| Complete the table by evaluating each expression using the example values: |Expression|Evaluates to| |---|---| |LENGTH(NUM_TO_STR(Multiplier))|| |MONTH(DoB) > 4|| |15 + STR_TO_NUM(MID(AddressLine[1], 2, 1))||
Show mark scheme

1(a) [3 marks]

Answers include: 1 They are tried and tested // Free from errors 2 They are readily available // Speed up development time 3 They will be updated automatically when improvements are made // No maintenance of routine is needed (as automatically updated) 4 The algorithm will be compliant with the international standard One mark per point Max 3

1(b)(i) [2 marks]

1 When a part of the algorithm performs a specific task 2 Part is repeated // performed in several places 3 Testing / debugging / maintenance is easier One mark for each point Max 2

1(b)(ii) [2 marks]

Term Description the name of the function Pass2 Count The parameter / value passed to the function The (data) type returned (by the function) BOOLEAN One mark per description (excluding first row)

1(c) [3 marks]

Expression Evaluates to LENGTH(NUM_TO_STR(Multiplier)) 3 TRUE MONTH(DoB) > 4 20 15 + STR_TO_NUM(MID(AddressLine[1], 2, 1)) One mark per row

Q1
May/Jun 2025 Paper 2 v3

A program is being developed for the management of a sports centre.

(a) The programmer developing the software decides to use modules (procedures or functions)

and local variables. They also decide not to use global variables.

(i) State two reasons why the programmer decides to use modules. 2 marks

1

2

(ii) State one difference between local and global variables. 1 mark

(iii) State two benefits of using local variables. 2 marks

1

2

(b) The pseudocode design contains a number of expressions. 5 marks

Complete each pseudocode expression so that it evaluates to the value shown.

Refer to the insert for the list of pseudocode functions and operators.

Expression Evaluates to
______(68) 'D'
______(04/02/2025) 2
______TRUE FALSE
( ("Court1.4Upper",,)) 1.4
A program is being developed for the management of a sports centre. ### (a) The programmer developing the software decides to use modules (procedures or functions) and local variables. They also decide not to use global variables. #### (i) State two reasons why the programmer decides to use modules. <span class="part-marks">2 marks</span> 1 2 #### (ii) State one difference between local and global variables. <span class="part-marks">1 mark</span> #### (iii) State two benefits of using local variables. <span class="part-marks">2 marks</span> 1 2 ### (b) The pseudocode design contains a number of expressions. <span class="part-marks">5 marks</span> Complete each pseudocode expression so that it evaluates to the value shown. Refer to the insert for the list of pseudocode functions and operators. |Expression|Evaluates to| |---|---| |______(68)|'D'| |______(04/02/2025)|2| |______TRUE|FALSE| |______(______ ("Court1.4Upper",______,______))|1.4|
Show mark scheme

1(a)(i) [2 marks]

MP1 When a task/module is repeated / reused / called // performed in several places MP2 A specific task can be identified /coded as a module / subroutine / procedure / function. MP3 Reduces complexity of program / code // Program / code is simplified MP4 Module / subroutine / procedure / function already available . MP5 Testing / debugging / maintenance is easier Max 2

1(a)(ii) [1 mark]

MP1 Local variables are used within a module // are accessible only within the module (in which they are declared) MP2 Global variables are accessible to all parts of the program / MP3 Local variables use memory only while the module in is executing // Global variables use memory for the whole time the program is running Max 1

1(a)(iii) [2 marks]

MP1 The same variable name can be reused in other parts of the program MP2 Using local variables makes modules self-contained // cannot accidentally change the same identifier outside of the module MP3 Using local variables aids modularisation . MP4 Memory allocated to local variables can be reused when module not in use Max 2

1(b) [5 marks]

Mark as follows: Expression Evaluates to Mark CHR (68) 'D' 1 MONTH (04/02/2025) 2 1 // -2 + DAY (04/02/2025) // -2023 + YEAR (04/02/2025) NOT TRUE FALSE 1 // FALSE = TRUE STR_TO_NUM(MID ("Court1.4Upper", 6,3 )) 1.4 2 Mark Row 4 as follows: 1 mark STR_TO_NUM 1 mark MID ("Court1.4Upper", 6,3 )

1(c) [2 marks]

Variable Data type MemberCount INTEGER TotalTakings REAL BookingConfirmed BOOLEAN MemberDOB DATE Mark as follows: 1 mark per row MP1 400

Q6
May/Jun 2025 Paper 2 v3

Study the structure chart:

Main
M
P
Sub_A Sub_B
V
R
X
W
T
U
Sub_Part1A Sub_Part2A Sub_Part3A Sub_Part1B Sub_Part2B
Sub_Part1A Sub_Part2B

Some of the parameter data types are:

  • R and V are of type INTEGER

  • T is of type REAL

  • U is of type STRING

  • W is of type BOOLEAN.

Some of the modules in the structure chart are functions, others are procedures.

(a) Explain one difference between functions and procedures. 1 mark

(b) Write the pseudocode to define the module headers: 5 marks

Sub_Part1A

Sub_Part2A

Sub_Part3A

(c) The structure chart uses the two symbols shown. 3 marks

Complete the table to explain what each symbol means and how the relevant modules in the structure chart are affected.

Symbol Explanation


______


______
Study the structure chart: |Main<br>M<br>P<br>Sub_A Sub_B<br>V<br>R<br>X<br>W<br>T<br>U<br>Sub_Part1A Sub_Part2A Sub_Part3A Sub_Part1B Sub_Part2B|| |---|---| |Sub_Part1A|Sub_Part2B| Some of the parameter data types are: - R and V are of type INTEGER - T is of type REAL - U is of type STRING - W is of type BOOLEAN. Some of the modules in the structure chart are functions, others are procedures. ### (a) Explain one difference between functions and procedures. <span class="part-marks">1 mark</span> ### (b) Write the pseudocode to define the module headers: <span class="part-marks">5 marks</span> Sub_Part1A Sub_Part2A Sub_Part3A ### (c) The structure chart uses the two symbols shown. <span class="part-marks">3 marks</span> Complete the table to explain what each symbol means and how the relevant modules in the structure chart are affected. |Symbol|Explanation| |---|---| ||______<br>______<br>______| ||______<br>______<br>______|
Show mark scheme

6(a) [1 mark]

MP1 A function returns a (single) value and a procedure does not MP2 A procedure can pass parameters by ByRef Max 1

6(b) [5 marks]

Sub_Part1A: 1 Mark PROCEDURE Sub_Part1A(R: INTEGER) Sub_Part2A: FUNCTION Sub_Part2A(T : REAL) RETURNS BOOLEAN 2 Marks Sub_Part3A: PROCEDURE Sub_Part3A(V: INTEGER, W: BOOLEAN, BYREF U : STRING) 2 Marks

6(c) [3 marks]

Symbol Explanation The module Main calls either Sub_A or Sub_B (which one is called is determined at run time) The module Sub_A will repeatedly call Sub_Part1A followed by Sub_Part2A then by Sub_Part3A MP1 Shape1: reference to selection MP2 Shape2: reference to repetition // iteration  MP3 Descption ( 2) including correct use of all module names in both parts

Q7
May/Jun 2025 Paper 2 v3

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

The programmer has decided that the following data items need to be stored for each customer:

Data item Description
customer ID a unique six-digit string
loyalty points an integer value that depends on how often the customer visits the coffee shop
last visit date the date the customer last visited the coffee shop

The programmer has defined a program module:

Module Description
UpdateVisit() • called with two parameters:
1. loyalty points of type INTEGER
2. last visit date of type DATE
• change the loyalty points:
 increase by four if the last visit date and the current date are in the
same month
 otherwise increase by one
• change the last visit date to the current date
• the changed values must be available to the code that follows the call
to UpdateVisit()

(a) (i) Write pseudocode for module UpdateVisit() 5 marks

Assume the customer has made at least one previous visit.

(ii) The programmer decides to amend the UpdateVisit() module so that loyalty points are further increased if the customer visits the coffee shop the same day of the week as their last visit. 1 mark

Write the pseudocode for this condition.

(b) A text file Loyalty.txt will be used to store the data items for the loyalty scheme.

The text file Loyalty.txt contains only one line of data for each customer.

Each data item is separated by a comma:

<CustomerID>,<LoyaltyPointsString>,<LastVisitDateString>

LastVisitDateString is always eight characters in length in the format: DDMMYYYY.

An example of how a line of data will be stored in the text file Loyalty.txt is:

"100123,132,05032025"

This example shows that the customer with an ID of 100123 had 132 loyalty points following their last visit to the coffee shop on 05/03/2025.

If a customer visits the coffee shop on a Monday, the value of their loyalty points is increased by 10.

The programmer has defined two more program modules:

Module Description
FindCustomer()
(is already written)
• called with a parameter of type STRING that represents a
customer ID
• returns the line of data read from the text file Loyalty.txt
containing the data items for that customer
MondayCheck() • called with a parameter of type STRING that represents the
customer ID of a customer
• calls FindCustomer()
• extracts the loyalty points from the string returned by
FindCustomer()
• increases the loyalty points for the current customer by 10 if the
day visited is a Monday
• returns an integer value representing the loyalty points

(i) Write pseudocode for module MondayCheck() 8 marks

The module FindCustomer() must be used and assume it returns a valid string for the current customer.

(ii) A date is stored in LastVisitDateString in the format: 4 marks

DDMMYYYY

DD is a 2-digit string MM is a 2-digit string YYYY is a 4-digit string.

For example, the date 03/09/2024 is stored as "03092024"

An algorithm is needed to convert the string stored in LastVisitDateString to data type DATE which is then stored in the variable LastVisitDate.

Complete the pseudocode for this algorithm:

Assume that LastVisitDateString has been declared and contains valid data.

DECLARE DayInt, MonthInt, YearInt : INTEGER

DECLARE LastVisitDate : DATE

A program is being developed to implement a customer loyalty scheme for a coffee shop. The programmer has decided that the following data items need to be stored for each customer: |Data item|Description| |---|---| |customer ID|a unique six-digit string| |loyalty points|an integer value that depends on how often the customer visits the coffee shop| |last visit date|the date the customer last visited the coffee shop| The programmer has defined a program module: |Module|Description| |---|---| |UpdateVisit()|• called with two parameters:<br>1. loyalty points of type INTEGER<br>2. last visit date of type DATE<br>• change the loyalty points:<br>  increase by four if the last visit date and the current date are in the<br>same month<br>  otherwise increase by one<br>• change the last visit date to the current date<br>• the changed values must be available to the code that follows the call<br>to UpdateVisit()| ### (a) (i) Write pseudocode for module UpdateVisit() <span class="part-marks">5 marks</span> Assume the customer has made at least one previous visit. #### (ii) The programmer decides to amend the UpdateVisit() module so that loyalty points are further increased if the customer visits the coffee shop the same day of the week as their last visit. <span class="part-marks">1 mark</span> Write the pseudocode for this condition. ### (b) A text file Loyalty.txt will be used to store the data items for the loyalty scheme. The text file Loyalty.txt contains only one line of data for each customer. Each data item is separated by a comma: &lt;CustomerID&gt;,&lt;LoyaltyPointsString&gt;,&lt;LastVisitDateString&gt; LastVisitDateString is always eight characters in length in the format: DDMMYYYY. An example of how a line of data will be stored in the text file Loyalty.txt is: "100123,132,05032025" This example shows that the customer with an ID of 100123 had 132 loyalty points following their last visit to the coffee shop on 05/03/2025. If a customer visits the coffee shop on a Monday, the value of their loyalty points is increased by 10. The programmer has defined two more program modules: |Module|Description| |---|---| |FindCustomer()<br>(is already written)|• called with a parameter of type STRING that represents a<br>customer ID<br>• returns the line of data read from the text file Loyalty.txt<br>containing the data items for that customer| |MondayCheck()|• called with a parameter of type STRING that represents the<br>customer ID of a customer<br>• calls FindCustomer()<br>• extracts the loyalty points from the string returned by<br>FindCustomer()<br>• increases the loyalty points for the current customer by 10 if the<br>day visited is a Monday<br>• returns an integer value representing the loyalty points| #### (i) Write pseudocode for module MondayCheck() <span class="part-marks">8 marks</span> The module FindCustomer() must be used and assume it returns a valid string for the current customer. #### (ii) A date is stored in LastVisitDateString in the format: <span class="part-marks">4 marks</span> DDMMYYYY DD is a 2-digit string MM is a 2-digit string YYYY is a 4-digit string. For example, the date 03/09/2024 is stored as "03092024" An algorithm is needed to convert the string stored in LastVisitDateString to data type DATE which is then stored in the variable LastVisitDate. Complete the pseudocode for this algorithm: Assume that LastVisitDateString has been declared and contains valid data. DECLARE DayInt, MonthInt, YearInt : INTEGER DECLARE LastVisitDate : DATE
Show mark scheme

7(a)(i) [5 marks]

Example solution: PROCEDURE UpdateVisit(BYREF LastVisitDate : DATE,__ BYREF LoyaltyPoints : INTEGER) IF MONTH(TODAY()) = MONTH(LastVisitDate) THEN  LoyaltyPoints LoyaltyPoints + 4 ELSE  LoyaltyPoints LoyaltyPoints + 1 ENDIF  LastVisitDate TODAY() ENDPROCEDURE MP1 Procedure heading and ending and two parameters of correct type MP2 … both passed BYREF MP3 Use of function to obtain current date TODAY()  MP4 Use function ( 2) and one parameter is the header parameter MONTH and 2nd parameter is / assigned variable TODAY() MP5 If visit is same month, increase by 4 otherwise LoyaltyPoints increase by 1 MP6 set to / ‘current date’ variable (assigned LastVisitDate TODAY() or unassigned) Max 5 DAYINDEX(LastVisitDate) = DAYINDEX(TODAY())

7(b)(i)

Alternative example solution: Uses a loop to calculate the number of digits in the string LoyaltyPoints FUNCTION MondayCheck(CustomerID : STRING) RETURNS INTEGER DECLARE LoyaltyPoints : INTEGER DECLARE LoyaltyPointsString : STRING DECLARE Index : INTEGER DECLARE Line : STRING  Line FindCustomer(CustomerID)  Index 9 WHILE MID(Line, Index, 1) <> ','  Index Index + 1 ENDWHILE // calculate the number of digits in LoyaltyPoints string  LoyaltyPointsString MID(Line, 8, Index - 8)  LoyaltyPoints STR_TO_NUM(LoyaltyPointsString) IF DAYINDEX(TODAY()) = 2 THEN  LoyaltyPoints LoyaltyPoints + 10 ENDIF RETURN LoyaltyPoints ENDFUNCTION

7(b)(ii) [4 marks]

Example solution:  DayInt STR_TO_NUM(LEFT(LastVisitDateString, 2))  MonthInt STR_TO_NUM(MID(LastVisitDateString, 3, 2))  YearInt STR_TO_NUM(RIGHT(LastVisitDateString, 4))  LastVisitDate SETDATE(DayInt, MonthInt, YearInt) Mark as follows: MP1 Use of one substring function MP2 , and all correctly extracted DayInt MonthInt YearInt MP3 Use of x 3 STR_TO_NUM MP4 function used to convert to a date type and assigned to SETDATE() LastVisitDate

Q2
Oct/Nov 2024 Paper 2 v1

A program uses three global integer variables HH, MM and SS to represent the current time in hours, minutes and seconds using the 24-hour clock notation.

Midnight would be represented as 00:00:00 (HH:MM:SS). If the variables HH, MM and SS contained the values 16, 30 and 10 respectively, then the time would be 16:30:10 or just after 4.30 in the afternoon.

A procedure Tick() will be called every second. The procedure Tick() will:

  • update the value in SS each time it is called

  • update the values in HH and MM as appropriate

  • call a procedure CheckAlarm() at the start of each minute

  • call a procedure NewDay() whenever the time reaches midnight.

Complete the pseudocode for procedure Tick().

PROCEDURE Tick()

ENDPROCEDURE 6 marks

A program uses three global integer variables HH, MM and SS to represent the current time in hours, minutes and seconds using the 24-hour clock notation. Midnight would be represented as 00:00:00 (HH:MM:SS). If the variables HH, MM and SS contained the values 16, 30 and 10 respectively, then the time would be 16:30:10 or just after 4.30 in the afternoon. A procedure Tick() will be called every second. The procedure Tick() will: - update the value in SS each time it is called - update the values in HH and MM as appropriate - call a procedure CheckAlarm() at the start of each minute - call a procedure NewDay() whenever the time reaches midnight. Complete the pseudocode for procedure Tick(). PROCEDURE Tick() ENDPROCEDURE <span class="part-marks">6 marks</span>
Show mark scheme

2 [6 marks]

Example solution: PROCEDURE Tick()  SS SS + 1 IF SS = 60 THEN  SS 0  MM MM + 1 IF MM = 60 THEN  MM 0  HH HH + 1 IF HH = 24 THEN  HH 0 CALL NewDay() ENDIF ENDIF CALL CheckAlarm() ENDIF ENDPROCEDURE Mark as follows: 1 Increment SS anywhere in the code 2 Call when SS is set to zero CheckAlarm() 3 Test if = 60 anywhere in the code … SS if so: 4 set to 0 SS 5 increment MM 6 When is set to 60 set to 0 and increment 7 When is set to 24 set to 0 and call NewDay() Max 6 marks

Q4
Oct/Nov 2024 Paper 2 v1

A program includes the following assignment statement:

Result ← STR_TO_NUM(x) / STR_TO_NUM(y)

When the program evaluates the expression in the statement, it performs a calculation.

Variable Result is of type real and variables x and y are of type string.

Two checks are required before the calculation is performed:

  1. The two strings represent valid numeric values.
  2. The numeric value of string y is not zero.

(a) Identify the type of error that could occur if these checks are not carried out and state a cause of this error. 2 marks

Type

Cause

(b) The designer considers implementing the checks and calculation as a module (a procedure or a function). One reason for this is that the same checks and calculations are performed at several places in the program. 2 marks

Give another reason why this is a suitable approach and state what is avoided by this approach.

Reason

Avoided

(c) The module to perform the checks and calculation will be implemented as a function. The function will need to return both a real and a Boolean value. To achieve this a record type is defined in pseudocode as follows: 6 marks

TYPE Result DECLARE Done : BOOLEAN DECLARE Value : REAL ENDTYPE

The function Evaluate() will:

  • take two parameters of type string representing the two numeric values

  • return a variable of type Result with the Done field set to FALSE if either of the following applies:

  • at least one of the strings does not represent a valid numeric value

  • the numeric value of the string representing value y is zero

  • otherwise return a variable of type Result with the Done field set to TRUE and the Value field assigned the result of the formula (based on the numeric value of the two parameters).

Write pseudocode for the function Evaluate().

A program includes the following assignment statement: Result ← STR_TO_NUM(x) / STR_TO_NUM(y) When the program evaluates the expression in the statement, it performs a calculation. Variable Result is of type real and variables x and y are of type string. Two checks are required before the calculation is performed: 1. The two strings represent valid numeric values. 2. The numeric value of string y is not zero. ### (a) Identify the type of error that could occur if these checks are not carried out and state a cause of this error. <span class="part-marks">2 marks</span> Type Cause ### (b) The designer considers implementing the checks and calculation as a module (a procedure or a function). One reason for this is that the same checks and calculations are performed at several places in the program. <span class="part-marks">2 marks</span> Give another reason why this is a suitable approach and state what is avoided by this approach. Reason Avoided ### (c) The module to perform the checks and calculation will be implemented as a function. The function will need to return both a real and a Boolean value. To achieve this a record type is defined in pseudocode as follows: <span class="part-marks">6 marks</span> TYPE Result DECLARE Done : BOOLEAN DECLARE Value : REAL ENDTYPE The function Evaluate() will: - take two parameters of type string representing the two numeric values - return a variable of type Result with the Done field set to FALSE if either of the following applies: - at least one of the strings does not represent a valid numeric value - the numeric value of the string representing value y is zero - otherwise return a variable of type Result with the Done field set to TRUE and the Value field assigned the result of the formula (based on the numeric value of the two parameters). Write pseudocode for the function Evaluate().
Show mark scheme

4(a) [2 marks]

One mark per point: Type: Run-time error Cause: A divide by zero operation is attempted // Attempt to convert a non- numeric string to a number

4(b) [2 marks]

Answers include: Reason: • This part of the algorithm performs a specific task // if the check or calculation is changed it is changed only once • A (similar) subroutine is already available // Library routine is already available • The program is simplified / easier to understand / easier to design / code / test / debug / maintain Max 1 marks for 'Reason' Avoided: • Unnecessary code duplication • Errors caused by differences where several copies of the check and calculation exist Max 1 marks for 'Avoided'

4(c) [6 marks]

Example solution: FUNCTION Evaluate(NumStr1, NumStr2 : STRING) RETURNS Result DECLARE RetVal : Result DECLARE Num1, Num2 : REAL  RetVal.Done FALSE IF IS_NUM(NumStr1) = TRUE AND IS_NUM(NumStr2) = TRUE THEN  Num1 STR_TO_NUM(NumStr1)  Num2 STR_TO_NUM(NumStr2) IF Num2 <> 0 THEN  RetVal.Value (Num1 / Num2)  RetVal.Done TRUE ENDIF ENDIF RETURN RetVal ENDFUNCTION Note that order of parameters is not specified so divisor could be either parameter. Mark as follows: 1 Function heading, parameters, ending 2 ... Correct return type of Result 3 Local declaration of type Result 4 Attempt at using to check both parameters/strings IS_NUM() 5 Attempt at using of to convert both parameters/strings STR_TO_NUM() 6 Check if the divisor, is non-zero ... 7 … and if so correct calculation and assignment to field Value 8 Return variable of type having assigned both fields Result Max 6 marks

Q7
Oct/Nov 2024 Paper 2 v1

A program contains six modules with headers as follows:

Pseudocode module header

PROCEDURE Connect()

FUNCTION Activate(H1 : STRING, Code : INTEGER) RETURNS BOOLEAN

FUNCTION Sync(T1 : BOOLEAN, S2 : REAL) RETURNS INTEGER

PROCEDURE Initialise(BYREF ID : INTEGER, BYVAL CC : INTEGER)

FUNCTION Reset(RA : STRING) RETURNS INTEGER

FUNCTION Enable(SA : INTEGER) RETURNS BOOLEAN

Module Connect() will call either Activate() or Sync(). This is decided at run-time.

(a) Complete the structure chart for these modules. 5 marks

Connect
T1
Connect
T1
Connect
T1

(b) Explain the meaning of the curved arrow symbol used in the diagram in part (a). 2 marks

A program contains six modules with headers as follows: Pseudocode module header PROCEDURE Connect() FUNCTION Activate(H1 : STRING, Code : INTEGER) RETURNS BOOLEAN FUNCTION Sync(T1 : BOOLEAN, S2 : REAL) RETURNS INTEGER PROCEDURE Initialise(BYREF ID : INTEGER, BYVAL CC : INTEGER) FUNCTION Reset(RA : STRING) RETURNS INTEGER FUNCTION Enable(SA : INTEGER) RETURNS BOOLEAN Module Connect() will call either Activate() or Sync(). This is decided at run-time. ### (a) Complete the structure chart for these modules. <span class="part-marks">5 marks</span> |Connect<br>T1||| |---|---|---| |Connect<br>T1||| |Connect<br>T1||| |||| ### (b) Explain the meaning of the curved arrow symbol used in the diagram in part (a). <span class="part-marks">2 marks</span>
Show mark scheme

7(a) [5 marks]

One mark per point: 1 All module identified in correct hierarchy 2 Parameters to both Sync and Activate and return values 3 Parameters to both Reset and Enable 4 Parameters to Initialise 5 Decision diamond

7(b) [2 marks]

Explanation: Means that Sync repeatedly calls Reset and (then) Enable One mark for each point: MP1: reference to iteration MP2: naming all three modules correctly including correct sequence of calls

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

Q6
May/Jun 2024 Paper 2 v1

Three points on a grid form a triangle with sides of length A, B and C as shown in the example:

y
A
C
B
A
C
B
A
C
B
A
C
B
A
C
B
A
C
B
A
C
B
A
C
B
A
C
B
A
C
B
C
B
A

0 1 2 3 4 5 6 7 8 9 10

x

A triangle is said to be right-angled if the following test is true (where A is the length of the longest side):

A [2] = B [2] + C [2]

A [2] means A multiplied by A, for example 3 [2] means 3 × 3 which evaluates to 9

You can calculate A [2], B [2] and C [2] by using the coordinates of the endpoints of each line.

For example, B [2] is calculated as follows:

y
B
P2
P1
(~~~~x1, ~~~~y1)
(~~~~x2, ~~~~y2)
B
P2
P1
(~~~~x1, ~~~~y1)
(~~~~x2, ~~~~y2)
B
P2
P1
(~~~~x1, ~~~~y1)
(~~~~x2, ~~~~y2)
B
P2
P1
(~~~~x1, ~~~~y1)
(~~~~x2, ~~~~y2)
B
P2
P1
(~~~~x1, ~~~~y1)
(~~~~x2, ~~~~y2)
B
P2
P1
(~~~~x1, ~~~~y1)
(~~~~x2, ~~~~y2)
B
P2
P1
(~~~~x1, ~~~~y1)
(~~~~x2, ~~~~y2)
B
P2
P1
(~~~~x1, ~~~~y1)
(~~~~x2, ~~~~y2)
B
P2
P1
(~~~~x1, ~~~~y1)
(~~~~x2, ~~~~y2)
B
P2
P1
(~~~~x1, ~~~~y1)
(~~~~x2, ~~~~y2)
2
(~~~~x2 , ~~~~y2 )
B
P1
(~~~~x 1, ~~~~y1

0 1 2 3 4 5 6 7 8 9 10

x

The endpoints, P1 and P2, have the coordinates (3, 2) and (6, 6).

The value B [2] is given by the formula:

B [2] = ( x 1 − x 2) [2] + ( y 1 − y 2) [2]

In this example:

B [2] = (3 − 6) [2] + (2 − 6) [2]

B [2] = (–3) [2] + (–4) [2]

B [2] = 9 + 16 B [2] = 25

(a) A function IsRA() will: 6 marks

  • take three sets of integers as parameters representing the coordinates of the three endpoints that form a triangle

  • return TRUE if the endpoints form a right-angled triangle, otherwise return FALSE .

In pseudocode, the operator ‘ ^ ’ represents an exponent, which is the number of times a value is multiplied by itself. For example, the expression Value [2] may be written in pseudocode as

    Value ^ 2

Complete the pseudocode for the function IsRA() .

    FUNCTION IsRA(x1, y1, x2, y2, x3, y3 : INTEGER) RETURNS BOOLEAN
    ENDFUNCTION

(b) The test used to check if a triangle is right-angled can be written in two ways: 2 marks

A [2] = B [2] + C [2]

or

A = √(B [2] + C [2] )

The symbol √ represents the square root operation. For example, √81 = 9

A new function SQRT() is written to perform the square root operation. The function takes an integer number as a parameter and returns a positive real value representing the square root of the number.

During testing it is found that the SQRT() function returns a value that is only accurate to 4 decimal places.

For example, SQRT(25) returns 5.0000125 rather than the correct value of 5.0

The function IsRA() from part (a) is modified to use the new SQRT() function to test if a triangle is right-angled.

Describe a problem that might occur when using the modified IsRA() function and suggest a solution that still allows the SQRT() function to be used.

Problem

Solution

Three points on a grid form a triangle with sides of length A, B and C as shown in the example: |y|||||||||| |---|---|---|---|---|---|---|---|---|---| |~~**A**~~<br>~~**C**~~<br>**B**|~~**A**~~<br>~~**C**~~<br>**B**|~~**A**~~<br>~~**C**~~<br>**B**|~~**A**~~<br>~~**C**~~<br>**B**|~~**A**~~<br>~~**C**~~<br>**B**|~~**A**~~<br>~~**C**~~<br>**B**|~~**A**~~<br>~~**C**~~<br>**B**|~~**A**~~<br>~~**C**~~<br>**B**|~~**A**~~<br>~~**C**~~<br>**B**|~~**A**~~<br>~~**C**~~<br>**B**| ||||||||||| ||||||||||| ||||||||||| ||||||||||| ||||||||~~**C**~~||| |||||**B**|||||| ||||||||||| ||||||~~**A**~~||||| ||||||||||| ||||||||||| 0 1 2 3 4 5 6 7 8 9 10 _x_ A triangle is said to be right-angled if the following test is true (where A is the length of the longest side): A [2] = B [2] + C [2] A [2] means A multiplied by A, for example 3 [2] means 3 × 3 which evaluates to 9 You can calculate A [2], B [2] and C [2] by using the coordinates of the endpoints of each line. For example, B [2] is calculated as follows: |y|||||||||| |---|---|---|---|---|---|---|---|---|---| |**B**<br>**P2**<br>**P1**<br>~~**(**~~~~**_x_**~~**1**~~**, **~~~~**_y_**~~**1**~~**)**~~<br>~~**(**~~~~**_x_**~~**2**~~**, **~~~~**_y_**~~**2**~~**)**~~|**B**<br>**P2**<br>**P1**<br>~~**(**~~~~**_x_**~~**1**~~**, **~~~~**_y_**~~**1**~~**)**~~<br>~~**(**~~~~**_x_**~~**2**~~**, **~~~~**_y_**~~**2**~~**)**~~|**B**<br>**P2**<br>**P1**<br>~~**(**~~~~**_x_**~~**1**~~**, **~~~~**_y_**~~**1**~~**)**~~<br>~~**(**~~~~**_x_**~~**2**~~**, **~~~~**_y_**~~**2**~~**)**~~|**B**<br>**P2**<br>**P1**<br>~~**(**~~~~**_x_**~~**1**~~**, **~~~~**_y_**~~**1**~~**)**~~<br>~~**(**~~~~**_x_**~~**2**~~**, **~~~~**_y_**~~**2**~~**)**~~|**B**<br>**P2**<br>**P1**<br>~~**(**~~~~**_x_**~~**1**~~**, **~~~~**_y_**~~**1**~~**)**~~<br>~~**(**~~~~**_x_**~~**2**~~**, **~~~~**_y_**~~**2**~~**)**~~|**B**<br>**P2**<br>**P1**<br>~~**(**~~~~**_x_**~~**1**~~**, **~~~~**_y_**~~**1**~~**)**~~<br>~~**(**~~~~**_x_**~~**2**~~**, **~~~~**_y_**~~**2**~~**)**~~|**B**<br>**P2**<br>**P1**<br>~~**(**~~~~**_x_**~~**1**~~**, **~~~~**_y_**~~**1**~~**)**~~<br>~~**(**~~~~**_x_**~~**2**~~**, **~~~~**_y_**~~**2**~~**)**~~|**B**<br>**P2**<br>**P1**<br>~~**(**~~~~**_x_**~~**1**~~**, **~~~~**_y_**~~**1**~~**)**~~<br>~~**(**~~~~**_x_**~~**2**~~**, **~~~~**_y_**~~**2**~~**)**~~|**B**<br>**P2**<br>**P1**<br>~~**(**~~~~**_x_**~~**1**~~**, **~~~~**_y_**~~**1**~~**)**~~<br>~~**(**~~~~**_x_**~~**2**~~**, **~~~~**_y_**~~**2**~~**)**~~|**B**<br>**P2**<br>**P1**<br>~~**(**~~~~**_x_**~~**1**~~**, **~~~~**_y_**~~**1**~~**)**~~<br>~~**(**~~~~**_x_**~~**2**~~**, **~~~~**_y_**~~**2**~~**)**~~| ||||||||||| ||||||||||| ||||||||||| ||||||**2**||||| |||||||~~**(**~~~~**_x_**~~**2**|~~**, **~~~~**_y_**~~**2**|~~**)**~~|| |||||**B**|||||| ||||||||||| |||**P1**|||||||| ||||~~**(**~~~~**_x_**~~|**1**~~**, **~~~~**_y_**~~**1**|||||| ||||||||||| 0 1 2 3 4 5 6 7 8 9 10 _x_ The endpoints, P1 and P2, have the coordinates (3, 2) and (6, 6). The value B [2] is given by the formula: B [2] = ( _x_ 1 − _x_ 2) [2] + ( _y_ 1 − _y_ 2) [2] In this example: B [2] = (3 − 6) [2] + (2 − 6) [2] B [2] = (–3) [2] + (–4) [2] B [2] = 9 + 16 B [2] = 25 ### (a) A function `IsRA()` will: <span class="part-marks">6 marks</span> - take three sets of integers as parameters representing the coordinates of the three endpoints that form a triangle - return `TRUE` if the endpoints form a right-angled triangle, otherwise return `FALSE` . In pseudocode, the operator ‘ `^` ’ represents an exponent, which is the number of times a value is multiplied by itself. For example, the expression Value [2] may be written in pseudocode as ``` Value ^ 2 ``` Complete the pseudocode for the function `IsRA()` . ``` FUNCTION IsRA(x1, y1, x2, y2, x3, y3 : INTEGER) RETURNS BOOLEAN ``` ``` ENDFUNCTION ``` ### (b) The test used to check if a triangle is right-angled can be written in two ways: <span class="part-marks">2 marks</span> A [2] = B [2] + C [2] or A = √(B [2] + C [2] ) The symbol √ represents the square root operation. For example, √81 = 9 A new function `SQRT()` is written to perform the square root operation. The function takes an integer number as a parameter and returns a positive real value representing the square root of the number. During testing it is found that the `SQRT()` function returns a value that is only accurate to 4 decimal places. For example, `SQRT(25)` returns 5.0000125 rather than the correct value of 5.0 The function `IsRA()` from part **(a)** is modified to use the new `SQRT()` function to test if a triangle is right-angled. Describe a problem that might occur when using the modified `IsRA()` function **and** suggest a solution that still allows the `SQRT()` function to be used. Problem Solution
Show mark scheme

6(a)

BOOLEAN DECLARE Len1, Len2, Len3 : INTEGER  Len1 (x1 - x2) ^ 2 + (y1 - y2) ^ 2  Len2 (x1 - x3) ^ 2 + (y1 - y3) ^ 2  Len3 (x2 - x3) ^ 2 + (y2 - y3) ^ 2 IF (Len1 = Len2 + Len3) OR__ (Len2 = Len1 + Len3) OR__ (Len3 = Len1 + Len2) THEN RETURN TRUE ELSE RETURN FALSE ENDIF ENDFUNCTION Mark as follows: 1 Calculate the square of the length of at least one side 2 Calculation of all three lengths squared correctly 3 One correct comparison of square of three lengths 4 All three comparisons… 5 combined using logical operators / nested // completely correct IF selection 6 Return result correctly in both cases

6(b) [2 marks]

1 mark for statement of problem: Problem:  The function will return an incorrect value // the test will fail 1 mark for solution: Solution:  Round the calculated values (to a known number of decimal places)  Define a threshold below which any difference can be ignored

Q7
May/Jun 2024 Paper 2 v1

A fitness club has a computerised membership system. The fitness club offers a number of different exercise classes.

The following information is stored for each club member: name, home address, email address, mobile phone number, date of birth and the exercise(s) they are interested in.

(a) When an exercise class is planned, a new module will send personalised text messages to each member who has expressed an interest in that exercise. Members wishing to join the class send a text message back. Members may decide not to receive future text messages by replying with the message ‘STOP’.

The process of abstraction is used to filter out unnecessary information.

(i) State one advantage of applying abstraction to this problem. 1 mark

(ii) Identify three items of information that will be required by the new module. 3 marks

Justify your choices with reference to the given scenario.

Item 1 required

Justification

Item 2 required

Justification

Item 3 required

Justification

(iii) Identify two operations that would be required to process data when the new module receives a text message back from a member. 2 marks

Operation 1

Operation 2

(b) The structure chart illustrates part of the membership program:

Update
A
P2
T1
Name
P1
Sub-A Sub-B Sub-C
Sub-A Sub-C

Data item notes:

  • Name contains the name of a club member

  • P1 and T1 are of type real.

(i) Explain the meaning of the diamond symbol (labelled with the letter A) in the chart. 2 marks

(ii) Write the pseudocode module headers for Sub-A and Sub-B. 4 marks

Sub-A

Sub-B

A fitness club has a computerised membership system. The fitness club offers a number of different exercise classes. The following information is stored for each club member: name, home address, email address, mobile phone number, date of birth and the exercise(s) they are interested in. ### (a) When an exercise class is planned, a new module will send personalised text messages to each member who has expressed an interest in that exercise. Members wishing to join the class send a text message back. Members may decide **not** to receive future text messages by replying with the message ‘STOP’. The process of abstraction is used to filter out unnecessary information. #### (i) State **one** advantage of applying abstraction to this problem. <span class="part-marks">1 mark</span> #### (ii) Identify **three** items of information that will be required by the new module. <span class="part-marks">3 marks</span> Justify your choices with reference to the given scenario. Item 1 required Justification Item 2 required Justification Item 3 required Justification #### (iii) Identify **two** operations that would be required to process data when the new module receives a text message back from a member. <span class="part-marks">2 marks</span> Operation 1 Operation 2 ### (b) The structure chart illustrates part of the membership program: |Update<br>A<br>P2<br>T1<br>Name<br>P1<br>Sub-A Sub-B Sub-C|| |---|---| |Sub-A|Sub-C| Data item notes: - Name contains the name of a club member - P1 and T1 are of type real. #### (i) Explain the meaning of the diamond symbol (labelled with the letter A) in the chart. <span class="part-marks">2 marks</span> #### (ii) Write the pseudocode module headers for Sub-A and Sub-B. <span class="part-marks">4 marks</span> Sub-A Sub-B
Show mark scheme

7(a)(i) [3 marks]

To make the solution easier to design / implement / solve

7(a)(ii)

One mark per item and justification Item: mobile phone number Justification: to send the text message Item: name Justification: to personalise the text message Item: exercise interest Justification: to determine whether this member would be interested

7(a)(iii) [2 marks]

Examples include:  Add a member to a list of those interested in the new class  Remove the member from future SMS messages  Read/process Message  Identify who from One mark for each. Max 2 marks

7(b)(i) [4 marks]

Means that calls (one of) either or Update Sub-A, Sub-B Sub-C One mark for each point:  reference to selection / decision / if  naming all four modules correctly PROCEDURE Sub-A (Name : STRING, BYREF P2 : BOOLEAN)

7(b)(ii) [8 marks]

FUNCTION Sub-B (P1 : REAL) RETURNS REAL One mark per underlined part in each case FUNCTION DeleteComment(Line : STRING) RETURNS STRING

Q8
May/Jun 2024 Paper 2 v1

A teacher is designing a program to process pseudocode projects written by her students.

Each student project is stored in a text file.

The process is split into a nu new file named as shown: umber of stages. Each stage performs a different task and cr
File name Comment
MichaelAday_src.txt student project file produced by student Michael Aday
MichaelAday_S1.txt file produced by stage 1
MichaelAday_S2.txt file produced by stage 2

The teacher has defined the first program module as follows:

Module Description
DeleteComment() • called with a parameter of type string representing a line of
pseudocode from a student’s project file
• returns the line after removing any comments
Note on comments:
A comment starts with two forward slash characters and includes all the
remaining characters on the line.
The following example shows a string before and after the comment has
been removed:
Before:IF X2 > 13 THEN //check if limit exceeded
After: IF X2 > 13 THEN

(a) Complete the pseudocode for module DeleteComment() . 8 marks

    FUNCTION DeleteComment(Line : STRING) RETURNS STRING
    ENDFUNCTION

(b) A second module is defined: 7 marks

Module Description
Stage_1() • called with a parameter of type string representing a student name
• creates a new stage 1 file
• copies each line from the student’s project file to the stage 1 file after
removing any comment from each line
• doesnot write blank lines to the stage 1 file
• returns the number of lines written to the stage 1 file

Write pseudocode for module Stage_1() .

Module DeleteComment() must be used in your solution.

A teacher is designing a program to process pseudocode projects written by her students. Each student project is stored in a text file. |The process is split into a nu new file named as shown:|umber of stages. Each stage performs a different task and cr| |---|---| |**File name**|**Comment**| |`MichaelAday_src.txt`|student project file produced by student Michael Aday| |`MichaelAday_S1.txt`|file produced by stage 1| |`MichaelAday_S2.txt`|file produced by stage 2| The teacher has defined the first program module as follows: |Module|Description| |---|---| |`DeleteComment()`|• called with a parameter of type string representing a line of<br>pseudocode from a student’s project file<br>• returns the line after removing any comments<br>Note on comments:<br>A comment starts with two forward slash characters and includes all the<br>remaining characters on the line.<br>The following example shows a string before and after the comment has<br>been removed:<br>Before:`IF X2 > 13 THEN //check if limit exceeded`<br>After: `IF X2 > 13 THEN`| ### (a) Complete the pseudocode for module `DeleteComment()` . <span class="part-marks">8 marks</span> ``` FUNCTION DeleteComment(Line : STRING) RETURNS STRING ``` ``` ENDFUNCTION ``` ### (b) A second module is defined: <span class="part-marks">7 marks</span> |Module|Description| |---|---| |`Stage_1()`|• called with a parameter of type string representing a student name<br>• creates a new stage 1 file<br>• copies each line from the student’s project file to the stage 1 file after<br>removing any comment from each line<br>• does**not** write blank lines to the stage 1 file<br>• returns the number of lines written to the stage 1 file| Write pseudocode for module `Stage_1()` . Module `DeleteComment()` must be used in your solution.
Show mark scheme

8(a) [7 marks]

DECLARE NewLine, TwoChars : STRING DECLARE Count, TrimTo : INTEGER CONSTANT Comment = "//"  NewLine Line  TrimTo 0  Count 1 WHILE Count < LENGTH(Line) AND TrimTo = 0  TwoChars MID(Line, Count, 2) // extract 2 chars IF TwoChars = Comment THEN  TrimTo Count ENDIF  Count Count + 1 ENDWHILE IF TrimTo <> 0 THEN  NewLine LEFT(Line, TrimTo - 1) ENDIF RETURN NewLine ENDFUNCTION Mark as follows: 1 Loop to length of (parameter) // length of Line Line -1 2 Terminate loop on first double slash 3 Attempt to extract one/two characters in a loop 4 Check for "//" after attempt at extraction in a loop 5 Record start position of comment // Calculate amount of trim required 6 Attempt to trim from start of comment Line 7 Completely correct trimmed from start of comment Line 8 Return after a reasonable overall attempt Line

8(b)

Example: FUNCTION Stage_1(StudentName : STRING) RETURNS INTEGER DECLARE OldFile, NewFile, Line : STRING DECLARE Count : INTEGER  OldFile StudentName & "_src.txt"  NewFile StudentName & "S1.txt" OPENFILE OldFile FOR READ OPENFILE NewFile FOR WRITE  Count 0 WHILE NOT EOF(OldFile) READFILE OldFile, Line  Line DeleteComment(Line) IF LENGTH(Line) <> 0 THEN WRITEFILE NewFile, Line  Count Count + 1 ENDIF ENDWHILE CLOSEFILE OldFile CLOSEFILE NewFile RETURN Count ENDFUNCTION Mark as follows: 1 Generate filenames condone missing “” 2 Open both files in correct modes and subsequently close 3 Loop to EOF(OldFile) 4 Read a line from and execute in a loop OldFile DeleteComment() 5 Skip blank lines after in a loop DeleteComment() 6 Write to stage 1 file and increment Count Line 7 Return the number of lines after a reasonable attempt at counting

Q8
May/Jun 2024 Paper 2 v2

A teacher is designing a program to process pseudocode projects written by her students.

Each student project is stored in a text file.

The process is split into a number of stages. Each stage performs a different task and creates a new file.

For example:
File name Comment
MichaelAday_src.txt Student project file produced by student Michael Aday
MichaelAday_S1.txt File produced by stage 1
MichaelAday_S2.txt File produced by stage 2

(a) Suggest a reason why the teacher’s program has been split into a number of stages and give the benefit of producing a different file from each stage. 2 marks

Reason

Benefit

(b) The teacher has defined the first program module as follows:

Module Description
DeleteSpaces() • called with a parameter of type string representing a line of
pseudocode from a student’s project file
• returns the line after removing any leading space characters
The following example shows a string before and after the leading
spaces have been removed:
Before:" IF X2 > 13 THEN"
After:"IF X2 > 13 THEN"

Complete the pseudocode for module DeleteSpaces() .

    FUNCTION DeleteSpaces(Line : STRING) RETURNS STRING

ENDFUNCTION [6]

(c) Two modules are defined: 8 marks

Module Description
DeleteComment()
(already written)
• called with a parameter of type string representing a line of
pseudocode from a student’s project file
• returns the line after removing any comment
Stage_2() • called with two parameters:
○ a string representing an input file name
○ a string representing an output file name
• copies each line from the input file to the existing output file having
first removed all leading spaces and comments from that line
• does not write blank lines to the output file
• outputs a final message giving the number of blank lines removed

Write pseudocode for module Stage_2() .

Modules DeleteComment() and DeleteSpaces() must be used in your solution.

A teacher is designing a program to process pseudocode projects written by her students. Each student project is stored in a text file. The process is split into a number of stages. Each stage performs a different task and creates a new file. |For example:|| |---|---| |**File name**|**Comment**| |`MichaelAday_src.txt`|Student project file produced by student Michael Aday| |`MichaelAday_S1.txt`|File produced by stage 1| |`MichaelAday_S2.txt`|File produced by stage 2| ### (a) Suggest a reason why the teacher’s program has been split into a number of stages **and** give the benefit of producing a different file from each stage. <span class="part-marks">2 marks</span> Reason Benefit ### (b) The teacher has defined the first program module as follows: |Module|Description| |---|---| |`DeleteSpaces()`|• called with a parameter of type string representing a line of<br>pseudocode from a student’s project file<br>• returns the line after removing any leading space characters<br>The following example shows a string before and after the leading<br>spaces have been removed:<br> Before:`"` `IF X2 > 13 THEN"`<br> After:`"IF X2 > 13 THEN"`| Complete the pseudocode for module `DeleteSpaces()` . ``` FUNCTION DeleteSpaces(Line : STRING) RETURNS STRING ``` `ENDFUNCTION` [6] ### (c) Two modules are defined: <span class="part-marks">8 marks</span> |Module|Description| |---|---| |`DeleteComment()`<br>(already written)|• called with a parameter of type string representing a line of<br>pseudocode from a student’s project file<br>• returns the line after removing any comment| |`Stage_2()`|• called with two parameters:<br> ○ a string representing an input file name<br> ○ a string representing an output file name<br>• copies each line from the input file to the existing output file having<br>first removed all leading spaces and comments from that line<br>• does not write blank lines to the output file<br>• outputs a final message giving the number of blank lines removed| Write pseudocode for module `Stage_2()` . Modules `DeleteComment()` and `DeleteSpaces()` must be used in your solution.
Show mark scheme

8(a) [6 marks]

One mark for reason, one for benefit Reason: (Program is) easier to design / implement / test / debug / modify Benefit: Easier to check that each stage works as expected

8(b) [8 marks]

Example algorithm based on finding position of first non-space character and then using substring function: FUNCTION DeleteSpaces(Line : STRING) RETURNS STRING DECLARE NewLine : STRING DECLARE EndOfLeading : BOOLEAN DECLARE Count, NumSpaces : INTEGER DECLARE NextChar : CHAR CONSTANT Space = " "  NumSpaces 0  EndOfLeading FALSE  FOR Count 1 TO LENGTH(Line)  NextChar MID(Line, Count, 1) IF NextChar <> Space AND EndOfLeading = FALSE THEN  NumSpaces Count - 1 // the number to trim EndOfLeading = TRUE ENDIF NEXT Count  NewLine RIGHT(Line, LENGTH(Line) - NumSpaces) RETURN NewLine ENDFUNCTION Mark as follows: 1 Loop to length of parameter // Loop until first non-space character in Line 2 Extract a character in a loop 3 Identify first non-space character in a loop 4 Attempt at removing leading spaces in Line 5 Leading spaces removed from / / Create new string without leading Line space 6 Return a string following a reasonable attempt at removing leading spaces in Line

8(c)

Example: PROCEDURE Stage_2(F1, F2 : STRING) DECLARE Line : STRING DECLARE Count : INTEGER  Count 0 OPEN F1 FOR READ OPEN F2 FOR APPEND WHILE NOT EOF(F1) READFILE F1, Line  Line DeleteSpaces(Line)  Line DeleteComment(Line) IF Line <> "" THEN WRITEFILE F2, Line // skip blank lines ELSE  Count Count + 1 ENDIF ENDWHILE CLOSEFILE F1 CLOSEFILE F2 OUTPUT Count, " blank lines were removed" ENDPROCEDURE Mark as follows: 1 Procedure heading, parameters, ending 2 Open both files in correct modes and subsequently close 3 Loop to EOF(F1) 4 Read a line from in a loop F1 5 Assign return values from and DeleteComment() DeleteSpaces() in a loop 6 Check return value following both MP5 function calls is not an empty string and if so write to in a loop F2 7 Count the blank lines in a loop 8 Output number of blank lines removed following a reasonable attempt after the loop

Q1
May/Jun 2024 Paper 2 v3

A program uses many complex algorithms.

One algorithm is repeated in several places. The code for the algorithm is the same wherever it is used, but the calculations within the algorithm may operate on different data.

The result of each calculation is used by the code that follows it.

It is decided to modify the program and implement the algorithm as a separate module.

(a) (i) State two benefits of this modification to the existing program. 2 marks

1

2

(ii) Describe how the modification would be implemented. 3 marks

A program uses many complex algorithms. One algorithm is repeated in several places. The code for the algorithm is the same wherever it is used, but the calculations within the algorithm may operate on different data. The result of each calculation is used by the code that follows it. It is decided to modify the program and implement the algorithm as a separate module. **(a) (i)** State **two** benefits of this modification to the existing program. <span class="part-marks">2 marks</span> 1 2 #### (ii) Describe how the modification would be implemented. <span class="part-marks">3 marks</span>
Show mark scheme

1(a)(i)

Two marks for the benefits:

  1. The code can be called when needed
  2. Any subsequent change to the algorithm / calculation needs to be made once only // Easier to manage / maintain (the program)
  3. Less code / no code duplication
  4. The algorithm / code / calculation can be designed / coded / tested once Note: Max 2 marks

1(a)(ii) [4 marks]

One mark per point:

  1. Create a module / function / procedure / subroutine using the (old) code / algorithm
  2. Replace the old code / algorithm wherever it appears with a call to the module / function / procedure / subroutine
  3. Pass the data as parameter(s) // Use of global variable(s)
  4. Return the result (of the calculation) // Assign result to global variable(s) / BYREF parameter(s)
  5. Create local variables as needed (to perform the calculation) Note: Max 3 marks

1(b) [5 marks]

Pseudocode expression Evaluates to "and" MID ("Random", 2, 3) 15 DAY 5 + (10/11/2023) TRUE IS_NUM ("45000") 3 MOD (20 3) + 1 One mark per row

Q7
May/Jun 2024 Paper 2 v3

Seven program modules form part of a program. A description of the relationship between the modules is summarised below. Any return values are stated in the description.

Module name Description
Mod-A calls Mod-B followed by Mod-C
Mod-B
called with parameters Par1 and Par2

calls either Mod-D or Mod-E, determined when the program runs

returns a Boolean value
Mod-C
called with parameters Par1 and Par3

Par3 is passed by reference

repeatedly calls Mod-F followed by Mod-G
Mod-D called with parameter Par2
Mod-E
called with parameter Par3

returns an integer value
Mod-F called with parameter Par3
Mod-G
called with parameter Par3

Par3 is passed by reference

Parameters in the table are as follows:

  • Par1 and Par3 are of type string.

  • Par2 is of type integer.

(a) (i) Identify the modules that would be implemented as functions. 1 mark

(ii) Modules Mod-F and Mod-G are both called with Par3 as a parameter. 2 marks

In the case of Mod-F, the parameter is passed by value. In the case of Mod-G, the parameter is passed by reference.

Explain the effect of the two different ways of passing the parameter Par3.

(b) Draw a structure chart to show the relationship between the seven modules and the parameters passed between them. 6 marks

Seven program modules form part of a program. A description of the relationship between the modules is summarised below. Any return values are stated in the description. |Module name|Description| |---|---| |Mod-A|calls Mod-B followed by Mod-C| |Mod-B|• <br>called with parameters Par1 and Par2<br>• <br>calls either Mod-D or Mod-E, determined when the program runs<br>• <br>returns a Boolean value| |Mod-C|• <br>called with parameters Par1 and Par3<br>• <br>Par3 is passed by reference<br>• <br>repeatedly calls Mod-F followed by Mod-G| |Mod-D|called with parameter Par2| |Mod-E|• <br>called with parameter Par3<br>• <br>returns an integer value| |Mod-F|called with parameter Par3| |Mod-G|• <br>called with parameter Par3<br>• <br>Par3 is passed by reference| Parameters in the table are as follows: - Par1 and Par3 are of type string. - Par2 is of type integer. **(a) (i)** Identify the modules that would be implemented as functions. <span class="part-marks">1 mark</span> #### (ii) Modules Mod-F and Mod-G are both called with Par3 as a parameter. <span class="part-marks">2 marks</span> In the case of Mod-F, the parameter is passed by value. In the case of Mod-G, the parameter is passed by reference. Explain the effect of the **two** different ways of passing the parameter Par3. ### (b) Draw a structure chart to show the relationship between the seven modules and the parameters passed between them. <span class="part-marks">6 marks</span>
Show mark scheme

7(a)(i) [2 marks]

Mod-B() and Mod-E()

7(a)(ii) [6 marks]

Points required: 1 any change made to the parameter value / within is Par3 Mod-G() reflected in the (subsequent) value in the calling module / (after Mod-C() terminates) Mod-G() 2 any change made to the parameter value / within is NOT Par3 Mod-F() reflected in the (subsequent) value in the calling module / (after Mod-C() terminates) Mod-F() Mark as follows: 1 mark for a reasonable attempt to explain 2 marks for full explanation including context

7(b) [7 marks]

One mark per bullet: 1 All modules correctly labelled and interconnected 2 Parameters between Mod-A and Mod-B and return value from Mod-B 3 Parameters between Mod-A and Mod-C 4 Diamond applied to Mod-B only 5 Iteration arrow applied to Mod-C only 6 All parameters at lower level and return value

Q8
May/Jun 2024 Paper 2 v3

A teacher is designing a program to process pseudocode projects written by her students.

The program analyses a student project and extracts information about each module that is defined (each procedure or function). This information is stored in a global 2D array ModInfo of type string.

A module header is the first line of a module definition and starts with either of the keywords PROCEDURE or FUNCTION.

An example of part of the array is given below. Row 10 of the array shows that a procedure header occurs on line 27 and row 11 shows that a function header occurs on line 35. "P" represents a procedure and "F" represents a function:

x = 1 x = 2 x = 3
"27" "P" "MyProc(Z : CHAR)"
"35" "F" "MyFun(Y : CHAR) RETURNS BOOLEAN"

The string stored in column 3 is called the module description. This is the module header without the keyword.

A valid module header will:

  • be at least 13 characters long

  • start with the keyword PROCEDURE or FUNCTION. The keyword may appear in either upper or lower case (or a mix of both) and must be followed by a space character.

The teacher has defined the first program module as follows:

Module Description
Header()
called with a parameter of type string representing a line of
pseudocode

if the line is a valid procedure header, returns a string:
"P"

if the line is a valid function header, returns a string:
"F"

otherwise, returns an empty string
For example, given the string:
"FUNCTION Zap(X : INTEGER) RETURNS CHAR"
Header()returns the string:
"FZap(X : INTEGER) RETURNS CHAR"

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

(b) A new module is required: 8 marks

Module Description
FindModules()
called with a parameter of type string representing a student
project file name

uses moduleHeader() to check each line of the project

assigns values to theModInfo array for each module
declaration in the student project

As a reminder, the previous example of part of the array is repeated below:

x = 1 x = 2 x = 3
"27" "P" "MyProc(Z : CHAR)"
"35" "F" "MyFun(Y : CHAR) RETURNS BOOLEAN"

Write pseudocode for module FindModules().

Assume that the array contains enough rows for the number of modules in each project.

A teacher is designing a program to process pseudocode projects written by her students. The program analyses a student project and extracts information about each module that is defined (each procedure or function). This information is stored in a global 2D array ModInfo of type string. A module header is the first line of a module definition and starts with either of the keywords PROCEDURE or FUNCTION. An example of part of the array is given below. Row 10 of the array shows that a procedure header occurs on line 27 and row 11 shows that a function header occurs on line 35. "P" represents a procedure and "F" represents a function: |x = 1|x = 2|x = 3| |---|---|---| |"27"|"P"|"MyProc(Z : CHAR)"| |"35"|"F"|"MyFun(Y : CHAR) RETURNS BOOLEAN"| The string stored in column 3 is called the module description. This is the module header **without** the keyword. A valid module header will: - be at least 13 characters long - start with the keyword PROCEDURE or FUNCTION. The keyword may appear in either upper or lower case (or a mix of both) and **must** be followed by a space character. The teacher has defined the first program module as follows: |Module|Description| |---|---| |Header()|• <br>called with a parameter of type string representing a line of<br>pseudocode<br>• <br>if the line is a valid procedure header, returns a string:<br> "P<Module description>"<br>• <br>if the line is a valid function header, returns a string:<br> "F<Module description>"<br>• <br>otherwise, returns an empty string<br> For example, given the string:<br> "FUNCTION Zap(X : INTEGER) RETURNS CHAR"<br> Header()returns the string:<br> "FZap(X : INTEGER) RETURNS CHAR"| ### (a) Write pseudocode for module Header(). <span class="part-marks">7 marks</span> ### (b) A new module is required: <span class="part-marks">8 marks</span> |Module|Description| |---|---| |FindModules()|• <br>called with a parameter of type string representing a student<br>project file name<br>• <br>uses moduleHeader() to check each line of the project<br>• <br>assigns values to theModInfo array for each module<br>declaration in the student project| As a reminder, the previous example of part of the array is repeated below: |x = 1|x = 2|x = 3| |---|---|---| |"27"|"P"|"MyProc(Z : CHAR)"| |"35"|"F"|"MyFun(Y : CHAR) RETURNS BOOLEAN"| Write pseudocode for module FindModules(). Assume that the array contains enough rows for the number of modules in each project.
Show mark scheme

8(a) [8 marks]

Example: FUNCTION Header(Line : STRING) RETURNS STRING IF LENGTH(Line) >= 13 THEN IF TO_UPPER(LEFT(Line, 9)) = "FUNCTION " THEN RETURN "F" & RIGHT(Line, LENGTH(Line) - 9) ENDIF IF TO_UPPER(LEFT(Line, 10)) = "PROCEDURE " THEN RETURN "P" & RIGHT(Line, LENGTH(Line) - 10) ENDIF ENDIF RETURN "" ENDFUNCTION Mark as follows: 1 Function heading, parameter, return type and ending 2 Check that the line is at least 13 characters long before attempting to extract and return empty string 3 Attempt at: Extract characters, 9 or 10 characters, corresponding to keyword plus space and compare with appropriate keyword plus space 4 Completely correct MP3 Use of type case conversion to allow for 'any case' 5 6 Calculation of 'rest of line' and concatenation with 'P or 'F' 7 Return string

8(b)

Example: PROCEDURE FindModules(FileName : STRING) DECLARE Line : STRING DECLARE Index, LineNum : INTEGER OPENFILE FileName FOR READ  Index 1  LineNum 0 WHILE NOT EOF(FileName) READFILE FileName, Line  LineNum LineNum + 1  Line Header(Line) IF Line <> "" THEN  ModInfo[Index, 1] NUM_TO_STR(LineNum)  ModInfo[Index, 2] LEFT(Line, 1)  ModInfo[Index, 3] RIGHT(Line, LENGTH(Line) - 1)  Index Index + 1 ENDIF ENDWHILE CLOSEFILE FileName ENDPROCEDURE Mark as follows: 1 Open file in mode and subsequently close READ 2 Loop to EOF(FileName) 3 Read a line from the file and maintain in a loop LineNum 4 Call and use return value in a loop Header() 5 Test return value for "" in a loop 6 Attempt at all three-array assignment for all columns in correct row 7 Correct values assigned to all columns of array 8 Maintain correct array row index

Q6
Oct/Nov 2023 Paper 2 v1

The pseudocode OUTPUT command starts each output on a new line.

(a) A new procedure MyOutput() will take a string and a Boolean parameter. 7 marks

MyOutput() may be called repeatedly and will use concatenation to build a string using a global variable MyString, up to a maximum length of 255 characters.

MyString will be output in either of these two cases:

  1. The Boolean parameter value is TRUE
  2. The resulting string (after concatenation) would be longer than 255 characters.

If MyString is not output, the string is concatenated with MyString .

For example, the calls to MyOutput() given below would result in the output as shown:

      MyOutput("Hello ", FALSE)
      MyOutput("ginger ", FALSE)
      MyOutput("cat", TRUE)
      MyOutput("How are you?", TRUE)

Resulting output:

      Hello ginger cat
      How are you?

Notes:

  • MyString is initialised to an empty string before MyOutput() is called for the first time.

  • No string passed to MyOutput() will be longer than 255 characters.

Write pseudocode for MyOutput() .

(b) The design of the procedure given in part (a) is modified and MyString is changed from a global to a local variable declared in MyOutput() . 2 marks

When the modified procedure is converted into program code, it does not work as expected.

Explain why it does not work as expected.

The pseudocode `OUTPUT` command starts each output on a new line. ### (a) A new procedure `MyOutput()` will take a string and a Boolean parameter. <span class="part-marks">7 marks</span> `MyOutput()` may be called repeatedly and will use concatenation to build a string using a global variable `MyString`, up to a maximum length of 255 characters. `MyString` will be output in either of these two cases: 1. The Boolean parameter value is `TRUE` 2. The resulting string (after concatenation) would be longer than 255 characters. If `MyString` is not output, the string is concatenated with `MyString` . For example, the calls to `MyOutput()` given below would result in the output as shown: ``` MyOutput("Hello ", FALSE) MyOutput("ginger ", FALSE) MyOutput("cat", TRUE) MyOutput("How are you?", TRUE) ``` Resulting output: ``` Hello ginger cat How are you? ``` Notes: - `MyString` is initialised to an empty string before `MyOutput()` is called for the first time. - No string passed to `MyOutput()` will be longer than 255 characters. Write pseudocode for `MyOutput()` . ### (b) The design of the procedure given in **part (a)** is modified and `MyString` is changed from a global to a local variable declared in `MyOutput()` . <span class="part-marks">2 marks</span> When the modified procedure is converted into program code, it does not work as expected. Explain why it does not work as expected.
Show mark scheme

6(a) [7 marks]

IF LENGTH(MyString) + LENGTH(NewString) > 255 THEN OUTPUT MyString // Resulting string would be too long  MyString NewString ELSE  MyString MyString & NewString // Concat with MyString IF EOL = TRUE THEN OUTPUT MyString  MyString "" ENDIF ENDIF ENDPROCEDURE MP1 Procedure heading, including parameters, and ending MP2 Produce concatenated string MP3 … Check whether resulting string would be too long MP4 If so, then output old MyString MP5 … and assign to NewString MyString MP6 Else concatenate to NewString MyString MP7 (test for length < 255) Test – If then Output EOL TRUE MP8 … and reset to empty string MyString MP1 A new (instance of) variable is created each time the

6(b) [2 marks]

MyString procedure is called / executed MP2 So the previous contents are lost

Q8
Oct/Nov 2023 Paper 2 v1

A class of students are developing a program to send data between computers. Many computers are connected together to form a wired network. Serial ports are used to connect one computer to another.

Each computer:

  • is assigned a unique three-digit ID

  • has three ports, each identified by an integer value

  • is connected to between one and three other computers.

Messages are sent between computers as a string of characters organised into fields as shown:

    <STX><DestinationID><SourceID><Data><ETX>

|Field<br>number|Field name|Description|
|---|---|---|
|n/a|`STX`|a single character marking the start of the message<br>(ASCII value 02)|
|1|`DestinationID`|three numeric characters that identify the destination computer|
|2|`SourceID`|three numeric characters that identify the source computer|
|3|`Data`|a variable length string containing the data being sent<br>(Minimum length is 1 character)|
|n/a|`ETX`|a single character marking the end of the message<br>(ASCII value 03)|

For example, the following message contains the data "Hello Kevin" being sent from computer "101" to computer "232":

    <STX>"232101Hello Kevin"<ETX>

Each computer will run a copy of the same program. Each program will contain a global variable, MyID of type string, that contains the unique ID of the computer in which the program is running.

The programmer has defined the first two program modules as follows:

Module Description
Transmit()
(already written)
• takes two parameters:
o a string containing a message
o an integer containing a port number
• transmits the message using the given port
SendFile() • takes three parameters:
o a string containing a text file name
o a string containing a Destination ID
o an integer containing a Port number
• transmits the file one line at a time
• transmits a final message with data string "****"

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

Assume:

  • module Transmit() has already been written and is used to transmit a message

  • the value of MyID may be used as SourceID

  • the file specified contains no blank lines

  • the file specified does not contain the line " **** "

(b) Module SendFile() is used to copy a file from one computer to another. 2 marks

A module within the program running on the destination computer will receive the data and write it to a new file.

Explain why module SendFile() transmits the message with data string "****" after the last line of the file.

(c) One of the text files to be sent contains several blank lines (lines that do not contain any text).

(i) Explain why this is a problem. 2 marks

(ii) Explain how the message format could be changed to allow a blank line to be sent. 2 marks 6 marks

Question 8(d) starts on page 18.

(d) A new module has b been defined:
Module Description
GetField() • takes two parameters:
o a string containing a message
o an integer containing a field number
• If the field number is valid (in the range 1 to 3, inclusive), it
returns a string containing the required field, otherwise it returns
an empty string.

As a reminder, a message is defined as follows:

      <STX><DestinationID><SourceID><Data><ETX>

|Field<br>number|Field name|Description|
|---|---|---|
|Not applicable|`STX`|a single character marking the start of the message<br>(ASCII value 02)|
|1|`DestinationID`|three numeric characters that identify the destination computer|
|2|`SourceID`|three numeric characters that identify the source computer|
|3|`Data`|a variable length string containing the data being sent<br>(Minimum length is 1 character)|
|Not applicable|`ETX`|a single character marking the end of the message<br>(ASCII value 03)|

Write pseudocode for module GetField() .

A class of students are developing a program to send data between computers. Many computers are connected together to form a wired network. Serial ports are used to connect one computer to another. Each computer: - is assigned a unique three-digit ID - has three ports, each identified by an integer value - is connected to between one and three other computers. Messages are sent between computers as a string of characters organised into fields as shown: ``` <STX><DestinationID><SourceID><Data><ETX> |Field<br>number|Field name|Description| |---|---|---| |n/a|`STX`|a single character marking the start of the message<br>(ASCII value 02)| |1|`DestinationID`|three numeric characters that identify the destination computer| |2|`SourceID`|three numeric characters that identify the source computer| |3|`Data`|a variable length string containing the data being sent<br>(Minimum length is 1 character)| |n/a|`ETX`|a single character marking the end of the message<br>(ASCII value 03)| ``` For example, the following message contains the data "Hello Kevin" being sent from computer "101" to computer "232": ``` <STX>"232101Hello Kevin"<ETX> ``` Each computer will run a copy of the same program. Each program will contain a global variable, `MyID` of type string, that contains the unique ID of the computer in which the program is running. The programmer has defined the first two program modules as follows: |Module|Description| |---|---| |`Transmit()`<br>(already written)|• takes two parameters:<br>`o `a string containing a message<br>`o `an integer containing a port number<br>• transmits the message using the given port| |`SendFile()`|• takes three parameters:<br>`o `a string containing a text file name<br>`o `a string containing a Destination ID<br>`o `an integer containing a Port number<br>• transmits the file one line at a time<br>• transmits a final message with data string "`****`"| ### (a) Write pseudocode for module `SendFile()` . <span class="part-marks">7 marks</span> Assume: - module `Transmit()` has already been written and is used to transmit a message - the value of `MyID` may be used as `SourceID` - the file specified contains no blank lines - the file specified does not contain the line " `****` " ### (b) Module `SendFile()` is used to copy a file from one computer to another. <span class="part-marks">2 marks</span> A module within the program running on the destination computer will receive the data and write it to a new file. Explain why module `SendFile()` transmits the message with data string `"****"` after the last line of the file. ### (c) One of the text files to be sent contains several blank lines (lines that do not contain any text). #### (i) Explain why this is a problem. <span class="part-marks">2 marks</span> #### (ii) Explain how the message format could be changed to allow a blank line to be sent. <span class="part-marks">2 marks</span> <span class="part-marks">6 marks</span> **Question 8(d) starts on page 18.** |(d) A new module has b|been defined:| |---|---| |**Module**|**Description**| |`GetField()`|• takes two parameters:<br>`o `a string containing a message<br>`o `an integer containing a field number<br>• If the field number is valid (in the range 1 to 3, inclusive), it<br>returns a string containing the required field, otherwise it returns<br>an empty string.| As a reminder, a message is defined as follows: ``` <STX><DestinationID><SourceID><Data><ETX> |Field<br>number|Field name|Description| |---|---|---| |Not applicable|`STX`|a single character marking the start of the message<br>(ASCII value 02)| |1|`DestinationID`|three numeric characters that identify the destination computer| |2|`SourceID`|three numeric characters that identify the source computer| |3|`Data`|a variable length string containing the data being sent<br>(Minimum length is 1 character)| |Not applicable|`ETX`|a single character marking the end of the message<br>(ASCII value 03)| ``` Write pseudocode for module `GetField()` .
Show mark scheme

8(a) [7 marks]

INTEGER) DECLARE FileData : STRING CONSTANT STX = CHR(02) CONSTANT ETX = CHR(03) OPENFILE FileName FOR READ WHILE NOT EOF(FileName) READFILE FileName, FileData  FileData STX & DestID & MyID & FileData & ETX CALL Transmit(FileData, Port) ENDWHILE CLOSEFILE FileName CALL Transmit(STX & DestID & MyID & "" & ETX, Port) ENDPROCEDURE Mark as follows: MP1 OPEN file in READ mode – using parameter - and subsequently CLOSE MP2 Conditional loop to EOF() MP3 Use of to get a line from the file READFILE MP4 ‘Attempt’ to form a message (minimum is ) DestID, MyID, FileData MP5 Message formed is completely correct MP6 Call with correct MP4 string in a loop Transmit() MP7 Transmit the "" message (all parts present) after the loop

8(b) [2 marks]

Max 2 marks MP1 Indicates that all the lines of the file have been sent // it is the end of the transmission / file transfer MP2 So that the receiving program can stop waiting for further data MP3 The file can be closed / saved

8(c)(i) [2 marks]

MP1 A message cannot contain a zero-length data field MP2 … so a blank line cannot be sent // there is no way to send a blank line

8(c)(ii) [2 marks]

MP1 Append a (special) character to the start of the message text MP2 interpret the new field data as a blank line ALTERNATIVE MP1 Change the message protocol and use an additional field to act as an indicator MP2 Interpret the new field data FUNCTION GetField(Msg : STRING, FieldNo : INTEGER)

8(d) [6 marks]

RETURNS STRING DECLARE RetString : STRING CASE OF FieldNo  1 : RetString MID(Msg, 2, 3)  2 : RetString MID(Msg, 5, 3)  3 : RetString MID(Msg, 8, LENGTH(Msg) - 8)  OTHERWISE : RetString "" ENDCASE RETURN RetString ENDFUNCTION MP1 Use of or CASE ... ENDCASE IF ... THEN ... ENDIF MP2 Field 1 and Field 2 extracted correctly MP3 Calculate a length of field 3 MP4 Field 3 extracted correctly MP5 Return empty string in case of invalid parameter (via or OTHERWISE initialisation) MP6 Final , after a reasonable attempt RETURN

Q6
Oct/Nov 2023 Paper 2 v2

(a) A procedure CreateFiles() will take two parameters: 6 marks

  • a string representing a file name

  • an integer representing the number of files to be created.

The procedure will create the number of text files specified.

Each file is given a different name. Each file name is formed by concatenating the file name with a suffix based on the file number. The suffix is always three characters.

For example, the call CreateFiles("TestData", 3) would result in the creation of the three files, TestData.001, TestData.002 and TestData.003.

Each file will contain a single line. For example, file TestData.002 would contain the string:

      This is File TestData.002

Write pseudocode for CreateFiles() .

Assume both parameters are valid and that the integer value is between 1 and 999, inclusive.

(b) A module CheckFiles() will count the number of files produced by CreateFiles() in part (a) .

CheckFiles() will take a string representing a file name and return the number of files found.

(i) Identify the type of module that should be used for CheckFiles() . 1 mark

(ii) Write the module header for CheckFiles() . 1 mark

(iii) State the file mode that should be used in CheckFiles() . 1 mark

### (a) A procedure `CreateFiles()` will take two parameters: <span class="part-marks">6 marks</span> - a string representing a file name - an integer representing the number of files to be created. The procedure will create the number of text files specified. Each file is given a different name. Each file name is formed by concatenating the file name with a suffix based on the file number. The suffix is always three characters. For example, the call `CreateFiles("TestData", 3)` would result in the creation of the three files, TestData.001, TestData.002 and TestData.003. Each file will contain a single line. For example, file TestData.002 would contain the string: ``` This is File TestData.002 ``` Write pseudocode for `CreateFiles()` . Assume both parameters are valid and that the integer value is between 1 and 999, inclusive. ### (b) A module `CheckFiles()` will count the number of files produced by `CreateFiles()` in part **(a)** . `CheckFiles()` will take a string representing a file name and return the number of files found. #### (i) Identify the type of module that should be used for `CheckFiles()` . <span class="part-marks">1 mark</span> #### (ii) Write the module header for `CheckFiles()` . <span class="part-marks">1 mark</span> #### (iii) State the file mode that should be used in `CheckFiles()` . <span class="part-marks">1 mark</span>
Show mark scheme

6(a) [6 marks]

Example Solution PROCEDURE CreateFiles(NameRoot : STRING, NumFiles : INTEGER) DECLARE FileName, Suffix : STRING DECLARE Count : INTEGER  FOR Count 1 TO NumFiles  Suffix NUM_TO_STR(Count) WHILE LENGTH(Suffix) <> 3  Suffix '0' & Suffix ENDWHILE  FileName NameRoot & '.' & Suffix OPENFILE FileName FOR WRITE WRITEFILE FileName, "This is File " & FileName CLOSEFILE FileName NEXT Count ENDPROCEDURE Mark as follows: 1 Procedure heading, including parameters, and ending 2 Loop for iterations NumFiles 3 Attempt to create filename suffix using in a loop NUM_TO_STR() 4 Completely correct filename 5 in mode and subsequent in a loop OPENFILE WRITE CLOSE 6 initial first line to the file in a loop WRITE

6(b)(i) [1 mark]

Function FUNCTION CheckFiles(NameRoot : STRING) RETURNS INTEGER

6(b)(iii) [1 mark]

Read

Q7
Oct/Nov 2023 Paper 2 v2

A program contains six modules:

Pseudocode module header

    PROCEDURE Module-A()
    PROCEDURE Module-X(T1 : INTEGER, S2 : REAL)
    PROCEDURE Reset(BYREF Code : INTEGER)
    FUNCTION Restore(OldCode : INTEGER) RETURNS BOOLEAN
    FUNCTION Module-Y(RA : INTEGER, RB : BOOLEAN) RETURNS BOOLEAN
    FUNCTION Module-Z(SA : INTEGER) RETURNS INTEGER

Module-X() calls Reset() Module-Y() calls Restore()

(a) Complete the structure chart for these modules. 4 marks

Module-A()

(b) Explain the meaning of the diamond symbol as used in the diagram in part (a) . 2 marks

A program contains six modules: **Pseudocode module header** ``` PROCEDURE Module-A() PROCEDURE Module-X(T1 : INTEGER, S2 : REAL) PROCEDURE Reset(BYREF Code : INTEGER) FUNCTION Restore(OldCode : INTEGER) RETURNS BOOLEAN FUNCTION Module-Y(RA : INTEGER, RB : BOOLEAN) RETURNS BOOLEAN FUNCTION Module-Z(SA : INTEGER) RETURNS INTEGER ``` `Module-X()` calls `Reset()` `Module-Y()` calls `Restore()` ### (a) Complete the structure chart for these modules. <span class="part-marks">4 marks</span> |Module-A()||| |---|---|---| |||| |||| |||| ### (b) Explain the meaning of the diamond symbol as used in the diagram in part **(a)** . <span class="part-marks">2 marks</span>
Show mark scheme

7(a) [4 marks]

One mark per point: 1 Module names 2 Parameters with labels to Module-X and between Module-X and Reset 3 Parameter (with label) to Module-Z and return from Module-Z 4 Parameters with labels to Module-Y and Restore and return values from Module-Y

7(b) [2 marks]

Means that calls either one of , or Module-A Module-X Module-Y Module- (which one is called is decided at runtime). Z One mark for reference to selection One mark for naming all four modules correctly

Q7
May/Jun 2023 Paper 2 v1

A school has a computerised library system that allows students to borrow books for a fixed length of time. The system uses text files to store details of students, books and loans.

A new module is to be written which will generate emails to each student who has an overdue book.

(a) Decomposition will be used to break down the problem of designing the new module into sub-problems. 3 marks

Identify three program modules that could be used in the design and describe their use.

Module 1

Use

Module 2

Use

Module 3

Use

(b) The program designer produces a structure chart for the new module. Part of the structure chart is shown:

(i) Explain the relationship between the four modules shown. 2 marks

(ii) Two new modules are added: Module‑X() and Module‑Y() . 3 marks

  • Module‑X() has no parameters.

  • Module‑Y() will take a string and a real number as parameters and return a Boolean value.

  • Module‑D() will call either Module‑X() or Module‑Y() .

Draw only the part of the structure chart that represents the relationship between Module‑X(), Module‑Y() and Module‑D() .

A school has a computerised library system that allows students to borrow books for a fixed length of time. The system uses text files to store details of students, books and loans. A new module is to be written which will generate emails to each student who has an overdue book. ### (a) Decomposition will be used to break down the problem of designing the new module into sub-problems. <span class="part-marks">3 marks</span> Identify **three** program modules that could be used in the design **and** describe their use. Module 1 Use Module 2 Use Module 3 Use ### (b) The program designer produces a structure chart for the new module. Part of the structure chart is shown: ![](../images/s23_21_q7_fig1.png) #### (i) Explain the relationship between the four modules shown. <span class="part-marks">2 marks</span> #### (ii) Two new modules are added: `Module‑X()` and `Module‑Y()` . <span class="part-marks">3 marks</span> - `Module‑X()` has no parameters. - `Module‑Y()` will take a string and a real number as parameters and return a Boolean value. - `Module‑D()` will call either `Module‑X()` or `Module‑Y()` . Draw **only** the part of the structure chart that represents the relationship between `Module‑X()`, `Module‑Y()` and `Module‑D()` .
Show mark scheme

7(a) [2 marks]

Examples include: Module: GetOverdueLoan() Use: Identifies an overdue book Module: IdentifyStudent() Use: Identifies a student (with an overdue book)1 Module: GetStudentEmail() Use: Gets the email address of a student with an overdue book Module: CreateEmail() Use: Generates an email to a student with an overdue book Module: SendEmail() Use: Sends an email to a student with an overdue book One mark for name and use Note: Max 3 marks

7(b)(i)

One mark per point:  Module-A calls the other three modules  The process is repeated

7(b)(ii) [7 marks]

One mark per bullet point:  All rectangles correctly labelled and interconnected  All and only parameters as shown  Selection diamond FUNCTION IsNewSupp(ThisString : STRING) RETURNS BOOLEAN

Q5
May/Jun 2023 Paper 2 v2

A programmer has produced the following pseudocode to output the square root of the numbers from 1 to 10.

Line numbers are for reference only.

10 DECLARE Num : REAL
...
40 REPEAT
41   CALL DisplaySqrt(Num)
42   Num  Num + 1.0
...
50 PROCEDURE DisplaySqrt(BYREF ThisNum : REAL)
51   OUTPUT ThisNum
52   ThisNum  SQRT(ThisNum)    // SQRT returns the square root
53   OUTPUT " has a square root of ", ThisNum
54 ENDPROCEDURE

The pseudocode is correctly converted into program code.

Function SQRT() is a library function and contains no errors.

The program code compiles without errors, but the program gives unexpected results. These are caused by a design error.

(a) Explain why the program gives unexpected results. 3 marks

(b) Explain why the compiler does not identify this error. 1 mark

(c) Describe how a typical Integrated Development Environment (IDE) could be used to identify this error. 3 marks

(d) The pseudocode is converted into program code as part of a larger program. 1 mark

During compilation, a complex statement generates an error.

The programmer does not want to delete the complex statement but wants to change the statement so that it is ignored by the compiler.

State how this may be achieved.

A programmer has produced the following pseudocode to output the square root of the numbers from 1 to 10. Line numbers are for reference only. ``` 10 DECLARE Num : REAL ``` ``` ... 40 REPEAT 41 CALL DisplaySqrt(Num) 42 Num Num + 1.0 ``` ``` ... 50 PROCEDURE DisplaySqrt(BYREF ThisNum : REAL) 51 OUTPUT ThisNum 52 ThisNum SQRT(ThisNum) // SQRT returns the square root 53 OUTPUT " has a square root of ", ThisNum 54 ENDPROCEDURE ``` The pseudocode is correctly converted into program code. Function `SQRT()` is a library function and contains no errors. The program code compiles without errors, but the program gives unexpected results. These are caused by a design error. ### (a) Explain why the program gives unexpected results. <span class="part-marks">3 marks</span> ### (b) Explain why the compiler does **not** identify this error. <span class="part-marks">1 mark</span> ### (c) Describe how a typical Integrated Development Environment (IDE) could be used to identify this error. <span class="part-marks">3 marks</span> ### (d) The pseudocode is converted into program code as part of a larger program. <span class="part-marks">1 mark</span> During compilation, a complex statement generates an error. The programmer does not want to delete the complex statement but wants to change the statement so that it is ignored by the compiler. State how this may be achieved.
Show mark scheme

5(a)

One mark per point:  parameter / has been passed by reference // should have been Num passed by value  so when the value / is modified (in procedure ThisNum ) DisplaySqrt()  the new value will be used in the loop (lines 40–43) // will be Num changed to modified value 

5(b) [1 mark]

The rules of the language have not been broken // there are no syntax errors

5(c) [1 mark]

Could use an IDE to:  Set a breakpoint to stop the program at a certain line / statement / point  Step through the program line by line / statement by statement  checking the value of / a variable using a report / watch window 'num' One mark per bullet

5(d) [6 marks]

Answers include:  Change the statement into a comment  Change the statement to a string representing a literal value and assign it to a variable / output it Note: max 1 mark

Q8
May/Jun 2023 Paper 2 v2

A computer shop assembles computers using items bought from several suppliers. A text file Stock.txt contains information about each item.

Information for each item is stored as a single line in the Stock.txt file in the format:

    <ItemNum><SupplierCode><Description>

||s as follows:||
|---|---|---|
||**Format**|**Comment**|
|`ItemNum`|4 numeric characters|unique number for each item in the range<br>″0001″ to ″5999″ inclusive|
|`SupplierCode`|3 alphabetic characters|to identify the supplier of the item|
|`Description`|a string|a minimum of 12 characters|

The file is organised in ascending order of ItemNum and does not contain all possible values in the range.

A programmer has started to define program modules as follows:

Module Description
OnlyAlpha()
(already written)

called with a parameter of type string

returnsTRUE if the string contains only alphabetic characters,
otherwise returnsFALSE
CheckInfo()
called with a parameter of type string representing a line of item
information

checks to see whether the item information in the string is valid

returnsTRUE if the item information is valid, otherwise returns
FALSE

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

Module OnlyAlpha() should be used as part of your solution.

(b) A new module is defined as follows: 7 marks

Module Description
AddItem()
called with a parameter of type string representing valid information
for a new item that is not currently in theStock.txt file

creates a new fileNewStock.txt from the contents of the file
Stock.txt and adds the new item information at the appropriate
place in theNewStock.txt file

As a reminder, the file Stock.txt is organised in ascending order of ItemNum and does not contain all possible values in the range.

Write pseudocode for module AddItem() .

(c) The program contains modules SuppExists() and CheckSupplier() . These have been written but contain errors. These modules are called from several places in the main program and testing of the main program (integration testing) has had to stop. 3 marks

Identify a method that can be used to continue testing the main program before the errors in these modules have been corrected and describe how this would work.

Method

Description

A computer shop assembles computers using items bought from several suppliers. A text file `Stock.txt` contains information about each item. Information for each item is stored as a single line in the `Stock.txt` file in the format: ``` <ItemNum><SupplierCode><Description> ||s as follows:|| |---|---|---| ||**Format**|**Comment**| |`ItemNum`|4 numeric characters|unique number for each item in the range<br>″0001″ to ″5999″ inclusive| |`SupplierCode`|3 alphabetic characters|to identify the supplier of the item| |`Description`|a string|a minimum of 12 characters| ``` The file is organised in ascending order of `ItemNum` and does **not** contain all possible values in the range. A programmer has started to define program modules as follows: |Module|Description| |---|---| |`OnlyAlpha()`<br>(already written)|• <br>called with a parameter of type string<br>• <br>returns`TRUE` if the string contains only alphabetic characters,<br>otherwise returns`FALSE`| |`CheckInfo()`|• <br>called with a parameter of type string representing a line of item<br>information<br>• <br>checks to see whether the item information in the string is valid<br>• <br>returns`TRUE` if the item information is valid, otherwise returns<br>`FALSE`| ### (a) Write pseudocode for module `CheckInfo()` . <span class="part-marks">7 marks</span> Module `OnlyAlpha()` should be used as part of your solution. ### (b) A new module is defined as follows: <span class="part-marks">7 marks</span> |Module|Description| |---|---| |`AddItem()`|• <br>called with a parameter of type string representing valid information<br>for a new item that is not currently in the`Stock.txt` file<br>• <br>creates a new file`NewStock.txt` from the contents of the file<br>`Stock.txt` and adds the new item information at the appropriate<br>place in the`NewStock.txt` file| As a reminder, the file `Stock.txt` is organised in ascending order of `ItemNum` and does not contain all possible values in the range. Write pseudocode for module `AddItem()` . ### (c) The program contains modules `SuppExists()` and `CheckSupplier()` . These have been written but contain errors. These modules are called from several places in the main program and testing of the main program (integration testing) has had to stop. <span class="part-marks">3 marks</span> Identify a method that can be used to continue testing the main program before the errors in these modules have been corrected **and** describe how this would work. Method Description
Show mark scheme

8(a) [7 marks]

DECLARE ThisNum : STRING DECLARE Index : INTEGER IF LENGTH(NewLine) < 19 THEN RETURN FALSE ENDIF  FOR Index 1 TO 4 IF NOT IS_NUM(MID(NewLine, Index, 1)) THEN RETURN FALSE ENDIF NEXT Index  ThisNum LEFT(Newline, 4) IF ThisNum < "0001" OR ThisNum > "5999" THEN RETURN FALSE ENDIF IF NOT OnlyAlpha(MID(Newline, 5, 3)) THEN RETURN FALSE ENDIF RETURN TRUE ENDFUNCTION Mark as follows: 1 Test length of parameter 2 Extract first 4 characters of parameter (as ) ItemNum 3 Test first four characters are all numeric 4 Test ItemNum in range "0001" to "5999" 5 Extract characters 5 to 7 of parameter (as ) SupplierCode 6 Use of with extracted OnlyAlpha() SupplierCode 7 Return value correctly in all cases, must have been declared BOOLEAN as local PROCEDURE AddItem(NewLine : STRING)

8(b) [3 marks]

Example of array-based solution: PROCEDURE AddItem(NewLine : STRING) DECLARE ThisItemNum, ThisLine : STRING DECLARE Temp : ARRAY [1:5999] OF STRING DECLARE Index : INTEGER  FOR Index 1 TO 5999  Temp[Index] "" //Initialise array NEXT Index  Index STR_TO_NUM(LEFT(NewLine, 4))  Temp[Index] NewLine //Add new line to array OPENFILE "Stock.txt" FOR READ WHILE NOT EOF("Stock.txt") READFILE("Stock.txt", ThisLine)  Index STR_TO_NUM(LEFT(ThisLine, 4))  Temp[Index] ThisLine //Add line from file to array ENDWHILE CLOSEFILE "Stock.txt" OPENFILE "NewStock.txt" FOR WRITE  FOR Index 1 TO 5999 IF Temp[Index] <> "" THEN //Write non-blank element... WRITEFILE("NewStock.txt", Temp[Index]) //...to new file ENDIF NEXT Index CLOSEFILE "NewStock.txt" ENDPROCEDURE Mark as follows: 1 Open both files, in correct modes, and subsequently close 2 Declare AND initialise array Temp 3 Store in appropriate array element NewLine 4 Loop until end of file Stock.txt 5 Read a line from AND extract in a loop Stock.txt Index 6 Assign line read to appropriate array element in a loop Loop through array, writing non-blank elements to file NewStock.txt 7

8(c)

One mark for method: Method: Stub testing Two marks for description:  The modules and are replaced by SuppExists() CheckSupplier() dummy modules  ...which return a known result / contain an output statement to show they have been called

Q6
May/Jun 2023 Paper 2 v3

A procedure Select() will:

  1. take two integer values as parameters representing start and end values where both values are greater than 9 and the end value is greater than the start value
  2. output each integer value between the start and the end value ( not including the start and end values), where the sum of the last two digits is 6, for example, 142.

(a) Write pseudocode for procedure Select() . 7 marks

Parameter validation is not required.

(b) The check performed by procedure Select() on the last two digits is needed at several places in the program and will be implemented using a new function. 4 marks

The new function CheckNum() will:

  • allow the required sum to be specified (not just 6)

  • check one number

  • return an appropriate value.

Describe the function interface and two advantages of this modular approach.

Interface

Advantage 1

Advantage 2

A procedure `Select()` will: 1. take two integer values as parameters representing start and end values where both values are greater than 9 and the end value is greater than the start value 2. output **each** integer value between the start and the end value ( **not** including the start and end values), where the sum of the last two digits is 6, for example, 142. ### (a) Write pseudocode for procedure `Select()` . <span class="part-marks">7 marks</span> Parameter validation is **not** required. ### (b) The check performed by procedure `Select()` on the last two digits is needed at several places in the program and will be implemented using a new function. <span class="part-marks">4 marks</span> The new function `CheckNum()` will: - allow the required sum to be specified (not just 6) - check one number - return an appropriate value. Describe the function interface **and two** advantages of this modular approach. Interface Advantage 1 Advantage 2
Show mark scheme

6(a) [4 marks]

Max 7 marks PROCEDURE Select(Start, End : INTEGER) DECLARE ThisNum, Total: INTEGER DECLARE ThisString : STRING DECLARE Char1, Char2 : CHAR  FOR ThisNum Start+1 TO End-1  ThisString NUM_TO_STR(ThisNum)  Char1 RIGHT(ThisString, 1)  Char2 LEFT(RIGHT(ThisString, 2), 1)  Total STR_TO_NUM(Char1) + STR_TO_NUM(Char2) IF Total = 6 THEN OUTPUT ThisString ENDIF NEXT ThisNum ENDPROCEDURE MP1 Procedure heading and ending MP2 (Count-controlled) Loop MP3 …. with correct range from Start+1 to End-1 MP4 Convert (loop counter) to a string ThisNum MP5 Extract the last two/first/second ’character digit(s)’ required in a loop MP6 Extract the second individual ‘character digit’ required in a loop MP7 Calculate the sum of the last two digits MP8 If sum = 6 then OUTPUT the number (either string or integer) in a loop

6(b)

Max 4 marks MP1 The function will take two integer parameters - the number and the (required) total MP2 … and return a Boolean OR: CheckNum(Number,Total : INTEGER) RETURNS BOOLEAN MP1 MP2 Two marks for the advantages: MP3 can be called repeatedly as and when required CheckNum() MP4 is designed and tested once (then used repeatedly) CheckNum() MP5 Any subsequent change to needs to be made once CheckNum() only // is easier to maintain/modify 

Q4
Oct/Nov 2022 Paper 2 v1

(a) The following diagram shows an Abstract Data Type (ADT) representation of an ordered linked list. The data item stored in each node is a single character. The data will be accessed in alphabetical order.

The symbol Ø represents a null pointer.

Start pointer

(i) Nodes with data 'A' and 'K' are added to the linked list. Nodes with data 'J' and 'L' are deleted. 4 marks

After the changes, the data items still need to be accessed in alphabetical order.

Complete the diagram to show the new state of the linked list.

(ii) The original data could have been stored in a 1D array in which each element stores a character. 2 marks

For example:

'C' 'J' 'L'

Explain the advantages of making the changes described in part (a)(i) when the data is stored in the linked list instead of an array.

### (a) The following diagram shows an Abstract Data Type (ADT) representation of an ordered linked list. The data item stored in each node is a single character. The data will be accessed in alphabetical order. The symbol Ø represents a null pointer. Start pointer #### (i) Nodes with data 'A' and 'K' are added to the linked list. Nodes with data 'J' and 'L' are deleted. <span class="part-marks">4 marks</span> After the changes, the data items still need to be accessed in alphabetical order. Complete the diagram to show the new state of the linked list. ![](../images/w22_21_q4_fig1.png) #### (ii) The original data could have been stored in a 1D array in which each element stores a character. <span class="part-marks">2 marks</span> For example: **'C'** **'J'** **'L'** Explain the advantages of making the changes described in **part (a)(i)** when the data is stored in the linked list instead of an array.
Show mark scheme

4(a)(i) [4 marks]

One mark for each: 1 Data A and K stored in new / existing nodes 2 Start pointer points to Node A 3 Node A points to Node C and Node C points to Node K 4 Node K contains Null Pointer

4(a)(ii) [2 marks]

One mark per point: 1 Pointers determine the ordering of data // only the pointers need to be changed when data changed 2 Easier to add / delete data (to maintain correct sequence) in a linked list // description of moving data to maintain correct sequence when array used

4(a)(iii) [2 marks]

One mark per point: 1 Need to store pointers as well as data 2 More complex (to setup / implement)

4(b) [4 marks]

One mark per point ( Max 4 ): 1 Declare two (1D) arrays 2 One for data, one for pointers 3 Elements from same index represent one node 4 Declare an integer / variable for // explain its use StartPointer 5 Define appropriate value for null pointer // explain its use 6 Declare an integer / variable for pointer // explain its use FreeList 7 Routines are needed to add / delete / search Alternative MP1, 2 and 3 for record-based implementation: 1 Define a record type with fields for data and pointer 2 Declare one (1D) array 3 ...of the defined record type

Q6
Oct/Nov 2022 Paper 2 v1

The following pseudocode algorithm attempts to check whether a string is a valid email address.

FUNCTION IsValid(InString : STRING) RETURNS BOOLEAN
DECLARE Index, Dots, Ats, Others : INTEGER
DECLARE NextChar : CHAR
DECLARE Valid : BOOLEAN
Index  1
### ← Dots  0
### ← Ats  0
### ← Others  0
### ← Valid  TRUE
### ←
REPEAT
NextChar  MID(InString, Index, 1)
### ← CASE OF NextChar '.' : Dots  Dots + 1
### ← '@' : Ats  Ats + 1
### ← IF Ats > 1 THEN Valid  FALSE
### ← ENDIF OTHERWISE : Others  Others + 1
### ← ENDCASE IF Dots > 1 AND Ats = 0 THEN Valid  FALSE
### ← ELSE Index  Index + 1
### ← ENDIF
  UNTIL Index > LENGTH(InString) OR Valid = FALSE
  IF NOT (Dots >= 1 AND Ats = 1 AND Others > 8) THEN
  Valid  FALSE
### ← ENDIF RETURN Valid ENDFUNCTION

(a) Part of the validation is implemented by the line: 1 mark

    IF NOT (Dots >= 1 AND Ats = 1 AND Others > 8) THEN

State the values that would result in the condition evaluating to TRUE . (b) (i) Complete the trace table by dry running the function when it is called as follows: 5 marks

Result ← I IsValid("Liz z.123@big@ne et")
Index NextChar Dots Ats Others Valid

(ii) State the value returned when IsValid() is called using the expression shown in part (b)(i) . 1 mark

The following pseudocode algorithm attempts to check whether a string is a valid email address. ``` FUNCTION IsValid(InString : STRING) RETURNS BOOLEAN DECLARE Index, Dots, Ats, Others : INTEGER DECLARE NextChar : CHAR DECLARE Valid : BOOLEAN ``` ``` Index 1 ### ← Dots 0 ### ← Ats 0 ### ← Others 0 ### ← Valid TRUE ### ← ``` ``` REPEAT NextChar MID(InString, Index, 1) ### ← CASE OF NextChar '.' : Dots Dots + 1 ### ← '@' : Ats Ats + 1 ### ← IF Ats > 1 THEN Valid FALSE ### ← ENDIF OTHERWISE : Others Others + 1 ### ← ENDCASE IF Dots > 1 AND Ats = 0 THEN Valid FALSE ### ← ELSE Index Index + 1 ### ← ENDIF ``` ``` UNTIL Index > LENGTH(InString) OR Valid = FALSE IF NOT (Dots >= 1 AND Ats = 1 AND Others > 8) THEN Valid FALSE ### ← ENDIF RETURN Valid ENDFUNCTION ``` ### (a) Part of the validation is implemented by the line: <span class="part-marks">1 mark</span> ``` IF NOT (Dots >= 1 AND Ats = 1 AND Others > 8) THEN ``` State the values that would result in the condition evaluating to `TRUE` . **(b) (i)** Complete the trace table by dry running the function when it is called as follows: <span class="part-marks">5 marks</span> |Result ← I|IsValid("Liz|z.123@big@ne|et")||| |---|---|---|---|---|---| |**`Index`**|**`NextChar`**|**`Dots`**|**`Ats`**|**`Others`**|**`Valid`**| ||||||| ||||||| ||||||| ||||||| ||||||| ||||||| ||||||| ||||||| ||||||| ||||||| ||||||| ||||||| ||||||| ||||||| ||||||| ||||||| ||||||| #### (ii) State the value returned when `IsValid()` is called using the expression shown in **part (b)(i)** . <span class="part-marks">1 mark</span>
Show mark scheme

6(a) [1 mark]

One mark for any part correct (accept equivalent wording) ( Max 1 ): • Condition evaluates to TRUE if bracket contents evaluate to FALSE: • Bracket contents evaluate to FALSE if: • Dots: zero / less than one or • Ats: not equal to one or • Others: less than nine One mark for each area as outlined:

6(b)(i) [5 marks]

Ats Index NextChar Dots Others Valid 0 0 0 TRUE 1 'L' 1 2 'i' 2 3 'z' 3 4 '.' 1 5 '1' 4 6 '2' 5 7 '3' 6 8 '@' 1 9 'b' 7 10 'i' 8 11 'g' 9 12 '@' 2 FALSE

6(b)(ii) [1 mark]

FALSE

Q6
Oct/Nov 2022 Paper 2 v2

(a) The factorial of an integer number is the product of all the integers from that number down to 1. 7 marks

In general, the factorial of n is n × (n−1) × ... × 2 × 1

For example, the factorial of 5 is 5 × 4 × 3 × 2 × 1 = 120

In this question, n will be referred to as the BaseNumber .

A function FindBaseNumber() will:

  • be called with a positive, non-zero integer value as a parameter

  • return BaseNumber if the parameter value is the factorial of the BaseNumber

  • return −1 if the parameter value is not a factorial.

For example:

Parameter value Value returned
120 5
12 −1
6 3
1 1

FindBaseNumber(12) will return −1 because 12 is not a factorial.

You may use the rest of this page for rough working.

Write pseudocode for the function FindBaseNumber() .

(b) A program is written to allow a user to input a sequence of values to be checked using the function FindBaseNumber() . 4 marks

The user will input one value at a time. The variable used to store the user input has to be of type string because the user will input ‘End’ to end the program.

Valid input will be converted to an integer and passed to FindBaseNumber() and the return value will be output.

Complete the table by giving four invalid strings that may be used to test distinct aspects of the required validation. Give the reason for your choice in each case.

Input Reason for choice


______


______


______


______
### (a) The factorial of an integer number is the product of all the integers from that number down to 1. <span class="part-marks">7 marks</span> In general, the factorial of n is n × (n−1) × ... × 2 × 1 For example, the factorial of 5 is 5 × 4 × 3 × 2 × 1 = 120 In this question, n will be referred to as the `BaseNumber` . A function `FindBaseNumber()` will: - be called with a positive, non-zero integer value as a parameter - return `BaseNumber` if the parameter value is the factorial of the `BaseNumber` - return −1 if the parameter value **is not** a factorial. For example: |Parameter value|Value returned| |---|---| |120|5| |12|−1| |6|3| |1|1| `FindBaseNumber(12)` will return −1 because 12 is not a factorial. You may use the rest of this page for rough working. Write pseudocode for the function `FindBaseNumber()` . ### (b) A program is written to allow a user to input a sequence of values to be checked using the function `FindBaseNumber()` . <span class="part-marks">4 marks</span> The user will input one value at a time. The variable used to store the user input has to be of type string because the user will input ‘End’ to end the program. Valid input will be converted to an integer and passed to `FindBaseNumber()` and the return value will be output. Complete the table by giving **four** invalid strings that may be used to test distinct aspects of the required validation. Give the reason for your choice in each case. |Input|Reason for choice| |---|---| ||______<br>______<br>______| ||______<br>______<br>______| ||______<br>______<br>______| ||______<br>______<br>______|
Show mark scheme

6(a)

Alternative FOR LOOP solution. Mark as follows: 1 Function heading and ending including parameter and return type 2 Declaration of local Integer value for and Num Try 3 Count-controlled Loop from 1 to ThisValue 4 Multiply by in a loop Try Num 5 Compare with in a loop Try ThisValue 6 ...Immediate return of if in a loop Num they are the same 7 Return –1 if not found after loop ThisValue FUNCTION FindBaseNumber(ThisValue : INTEGER) RETURNS INTEGER DECLARE Num, Try : INTEGER  Try 1  FOR Num 1 TO ThisValue  Try Try * Num IF Try = ThisValue THEN //BaseNumber found RETURN Num ENDIF NEXT Num RETURN -1 ENDFUNCTION

6(b) [4 marks]

One mark per row. Examples of invalid strings: 1 Non-numeric but not "End" // contains space or other non-numeric characters 2 Real number 3 Integer value out of range (i.e. <= 0) 4 Empty string 5 Correct word but wrong case e.g. "end" rather than "End" Input Reason for choice "Aardvark" Non-numeric (and not "End") "27.3" Numeric but not an integer "-3" // "0" A non-positive integer "" An empty string

Q6
Oct/Nov 2022 Paper 2 v3

Components are weighed during manufacture. Weights are measured to the nearest whole gram.

Components that weigh at least 3 grams more than the maximum weight, or at least 3 grams less than the minimum weight, are rejected.

A component is rechecked if it weighs within 2 grams of either the maximum or minimum weight.

The final outcome of weighing each component is shown below:

Outcome Weight

Reject

Accept

Recheck

Reject

A function Status() will be called with three parameters. These are integers representing the weight of an individual component together with the minimum and maximum weights.

unction will be as follows:
Outcome Return value
Accept 'A'
Reject 'R'
Recheck 'C'

(a) Complete the following test plan for five tests that could be performed on function Status() . 5 marks

The tests should address all possible outcomes.

Test number Component weight Min Max Expected return value
1 'A'
2
3
4
5

(b) Write pseudocode for Status() . 6 marks

Components are weighed during manufacture. Weights are measured to the nearest whole gram. Components that weigh at least 3 grams more than the maximum weight, or at least 3 grams less than the minimum weight, are rejected. A component is rechecked if it weighs within 2 grams of either the maximum or minimum weight. The final outcome of weighing each component is shown below: **Outcome** **Weight** Reject ![](../images/w22_23_q6_fig1.png) Accept Recheck Reject ![](../images/w22_23_q6_fig2.png) A function `Status()` will be called with three parameters. These are integers representing the weight of an individual component together with the minimum and maximum weights. |unction will be|as follows:| |---|---| |**Outcome**|**Return value**| |Accept|`'A'`| |Reject|`'R'`| |Recheck|`'C'`| ### (a) Complete the following test plan for **five** tests that could be performed on function `Status()` . <span class="part-marks">5 marks</span> The tests should address all possible outcomes. |Test number|Component weight|Min|Max|Expected return value| |---|---|---|---|---| |1||||`'A'`| |2||||| |3||||| |4||||| |5||||| ### (b) Write pseudocode for `Status()` . <span class="part-marks">6 marks</span>
Show mark scheme

6(a) [5 marks]

One mark per row Examples: Test Component Expected return Min Max number weight value 1 300 290 315 'A' 2

317 290 315 'R' 3 317 290 315 'C' 4 288 290 315 'C' 5 < 288 290 315 'R'

6(b) [6 marks]

One mark per point: 1 Function heading and ending including parameters 2 Declaration of local variable for Result / alt mechanism 3 Check for Reject 4 Check for Accept 5 Check for Recheck (or just default to third option) 6 Return Result following a reasonable attempt Function Status(Actual, Min, Max : INTEGER) RETURNS CHAR DECLARE Result : CHAR CONSTANT Accept = 'A' CONSTANT Reject = 'R' CONSTANT ReCheck = 'C'  Result ReCheck //Check if reject IF Actual > Max + 2 OR Actual < Min – 2 THEN  Result Reject ENDIF //Check if acceptable IF Actual < Max - 2 AND Actual > Min + 2 THEN  Result Accept ENDIF RETURN Result ENDFUNCTION

Q3
May/Jun 2022 Paper 2 v1

The manager of a cinema wants a program to allow users to book seats. The cinema has several screens. Each screen shows a different film.

(a) Decomposition will be used to break the problem down into sub-problems. 3 marks

Describe three program modules that could be used in the design.

Module 1

Module 2

Module 3

(b) Two types of program modules may be used in the design of the program. 1 mark

Identify the type of program module that should be used to return a value.

The manager of a cinema wants a program to allow users to book seats. The cinema has several screens. Each screen shows a different film. ### (a) Decomposition will be used to break the problem down into sub-problems. <span class="part-marks">3 marks</span> Describe **three** program modules that could be used in the design. Module 1 Module 2 Module 3 ### (b) Two types of program modules may be used in the design of the program. <span class="part-marks">1 mark</span> Identify the type of program module that should be used to return a value.
Show mark scheme

3(a) [3 marks]

One mark per description of appropriate sub-problem for given scenario. Examples include:  Allows the user to search for films being shown // input name of film they want to see  Allows the user to search for available seats  Calculate cost of booking  Book a given number of seats for a particular screening

3(b) [1 mark]

Function

Q8
May/Jun 2022 Paper 2 v1

A program allows a user to save passwords used to login to websites. A stored password is inserted automatically when the user logs into the corresponding website.

A student is developing a program to generate a password. The password will be of a fixed format, consisting of three groups of four alphanumeric characters. The groups are separated by the hyphen character '-'.

An example of a password is: "FxAf-3haV-Tq49"

A global 2D array Secret of type STRING stores the passwords together with the website domain name where they are used. Secret contains 1000 elements organised as 500 rows by 2 columns.

Unused elements contain the empty string ( "" ). These may occur anywhere in the array.

Note:

part of the array is:
Array element Value
Secret[27, 1] "www.thiswebsite.com"
Secret[27, 2] ""
Secret[28, 1] "www.thatwebsite.com"
Secret[28, 2] ""
  • For security, passwords are stored in an encrypted form, shown as "  " in the example.

  • The passwords cannot be used without being decrypted.

  • Assume that the encrypted form of a password will not be an empty string.

The programmer has started to define program modules as follows:

Module Description
RandomChar()
Generates a single random character from within one of the
following ranges:


'a' to 'z'


'A' to 'Z'


'0' to '9'

Returns the character
Encrypt()
Takes a password as a parameter of type string

Returns the encrypted form of the password as a string
Decrypt()
Takes an encrypted password as a parameter of type string

Returns the decrypted form of the password as a string

For reference, relevant ASCII values are as follows:

Character range ASCII range
'a' to 'z' 97 to 122
'A' to 'Z' 65 to 90
'0' to '9' 48 to 57

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

You may wish to refer to the insert for a description of the CHR() function. Other functions may also be required.

(b) A new module is defined as follows: 7 marks

Module Description
FindPassword()
Takes a website domain name as a parameter of type string

Searches for the website domain name in the arraySecret

If the website domain name is found, the decrypted password
is returned

If the website domain name is not found, a warning message
is output, and an empty string is returned

Write pseudocode for module FindPassword() .

Assume that modules Encrypt() and Decrypt() have already been written.

(c) The modules Encrypt() and Decrypt() are called from several places in the main program. 3 marks

Identify a method that could have been used to test the main program before these modules were completed. Describe how this would work.

Method

Description

(d) A validation function is written to check that the passwords generated are valid. 2 marks

To be valid, each password must:

  • be 14 characters long

  • be organised as three groups of four case-sensitive alphanumeric characters. The groups are separated by hyphen characters

  • not include any duplicated characters, except for the hyphen characters.

Note: lower-case and upper-case characters are not the same. For example, 'a' is not the same as 'A'.

Give two password strings that could be used to test different areas of the validation rules.

Password 1

Password 2

(e) The RandomChar() module is to be modified so that alphabetic characters are generated twice as often as numeric characters. 3 marks

Describe how this might be achieved.

A program allows a user to save passwords used to login to websites. A stored password is inserted automatically when the user logs into the corresponding website. A student is developing a program to generate a password. The password will be of a fixed format, consisting of **three groups of four** alphanumeric characters. The groups are separated by the hyphen character '-'. An example of a password is: "FxAf-3haV-Tq49" A global 2D array `Secret` of type `STRING` stores the passwords together with the website domain name where they are used. `Secret` contains 1000 elements organised as 500 rows by 2 columns. Unused elements contain the empty string ( `""` ). These may occur anywhere in the array. Note: |part of the array is:|| |---|---| |**Array element**|**Value**| |`Secret[27, 1]`|"www.thiswebsite.com"| |`Secret[27, 2]`|`"``"`| |`Secret[28, 1]`|"www.thatwebsite.com"| |`Secret[28, 2]`|`"``"`| - For security, passwords are stored in an encrypted form, shown as `"`  `"` in the example. - The passwords cannot be used without being decrypted. - Assume that the encrypted form of a password will **not** be an empty string. The programmer has started to define program modules as follows: |Module|Description| |---|---| |`RandomChar()`|• <br>Generates a single random character from within one of the<br>following ranges:<br> <br>○<br>'a' to 'z'<br> <br>○<br>'A' to 'Z'<br> <br>○<br>'0' to '9'<br>• <br>Returns the character| |`Encrypt()`|• <br>Takes a password as a parameter of type string<br>• <br>Returns the encrypted form of the password as a string| |`Decrypt()`|• <br>Takes an encrypted password as a parameter of type string<br>• <br>Returns the decrypted form of the password as a string| For reference, relevant ASCII values are as follows: |Character range|ASCII range| |---|---| |'a' to 'z'|97 to 122| |'A' to 'Z'|65 to 90| |'0' to '9'|48 to 57| ### (a) Write pseudocode for module `RandomChar()` . <span class="part-marks">6 marks</span> You may wish to refer to the **insert** for a description of the `CHR()` function. Other functions may also be required. ### (b) A new module is defined as follows: <span class="part-marks">7 marks</span> |Module|Description| |---|---| |`FindPassword()`|• <br>Takes a website domain name as a parameter of type string<br>• <br>Searches for the website domain name in the array`Secret`<br>• <br>If the website domain name is found, the decrypted password<br>is returned<br>• <br>If the website domain name is not found, a warning message<br>is output, and an empty string is returned| Write pseudocode for module `FindPassword()` . Assume that modules `Encrypt()` and `Decrypt()` have already been written. ### (c) The modules `Encrypt()` and `Decrypt()` are called from several places in the main program. <span class="part-marks">3 marks</span> Identify a method that could have been used to test the main program before these modules were completed. Describe how this would work. Method Description ### (d) A validation function is written to check that the passwords generated are valid. <span class="part-marks">2 marks</span> To be valid, each password must: - be 14 characters long - be organised as three groups of four case-sensitive alphanumeric characters. The groups are separated by hyphen characters - not include any duplicated characters, except for the hyphen characters. Note: lower-case and upper-case characters are not the same. For example, 'a' is not the same as 'A'. Give **two** password strings that could be used to test different areas of the validation rules. Password 1 Password 2 ### (e) The `RandomChar()` module is to be modified so that alphabetic characters are generated twice as often as numeric characters. <span class="part-marks">3 marks</span> Describe how this might be achieved.
Show mark scheme

8(a) [7 marks]

DECLARE ThisRange : INTEGER DECLARE ThisChar : CHAR //First select the range  ThisRange INT(RAND(3)) + 1 // 1 to 3 CASE OF ThisRange  1: ThisChar CHR(INT(RAND(26) + 65)) // 65 to 90: 'A' to 'Z'  ThisChar LCASE(ThisChar) // 'a' to 'z'  2: ThisChar CHR(INT(RAND(26) + 65)) // 65 to 90: A to Z  3: ThisChar NUM_TO_STR(INT(RAND(10)) // '0' to '9' ENDCASE RETURN ThisChar ENDFUNCTION Mark as follows: 1 Generation of any integer random number 2 Randomly decide which of the three ranges to select 3 Selection structure based on range 4 One alphanumeric character range correct 5 All alphanumeric character ranges correct 6 Return , following a reasonable attempt to generate a ThisChar character in each range FUNCTION FindPassword(Name: STRING) RETURNS STRING

8(b)

DECLARE Index : INTEGER DECLARE Password : STRING  Password ""  Index 1 WHILE Password = "" AND Index <= 500 IF Secret[Index, 1] = Name THEN  Password Decrypt(Secret[Index, 2]) ELSE  Index Index + 1 ENDIF ENDWHILE IF Password = "" THEN OUTPUT "Domain name not found" ENDIF RETURN Password ENDFUNCTION Mark as follows: 1 Declare all local variables used, attempted solution has to be reasonable 2 Conditional loop while not found and not end of array 3 Compare value of element in column 1 with parameter passed into function 4 ...and use Decrypt with element in column 2 as parameter () 5 …use the return value of Decrypt() 6 Output warning message if parameter not found 7 Return value STRING

8(c) [3 marks]

One mark for the name, one for the description Name:  Stub testing Description:  A simple module is written to replace each of the modules.  The simple module will return an expected value // will output a message to show they have been called

8(d) [2 marks]

Accept one example of a valid password to Max 2 One mark for each password example that breaks one of the rules due to:  Length too long // length too short  Invalid character  Incorrect grouping (including number of hyphens)  Duplicated characters

8(e) [3 marks]

One mark for each part:  Generate a random integer divisible by 3  Split range into 1/3 and set as numeric  Else alphabetic character

Q7
May/Jun 2022 Paper 2 v2

A programming language has string functions equivalent to those given in the insert .

The language includes a LEFT() and a RIGHT() function, but it does not have a MID() function.

(a) Write pseudocode for an algorithm to implement your own version of the MID() function which will operate in the same way as that shown in the insert . 4 marks

Do not use the MID() function given in the insert, but you may use any of the other functions.

Assume that the values passed to the function will be correct.

(b) The values passed to your MID() function in part (a) need to be validated. 2 marks

Assume that the values are of the correct data type.

State two checks that could be applied to the values passed to the function.

1

2

A programming language has string functions equivalent to those given in the **insert** . The language includes a `LEFT()` and a `RIGHT()` function, but it does **not** have a `MID()` function. ### (a) Write pseudocode for an algorithm to implement your own version of the `MID()` function which will operate in the same way as that shown in the **insert** . <span class="part-marks">4 marks</span> Do **not** use the `MID()` function given in the **insert**, but you may use any of the other functions. Assume that the values passed to the function will be correct. ### (b) The values passed to your `MID()` function in **part (a)** need to be validated. <span class="part-marks">2 marks</span> Assume that the values are of the correct data type. State **two** checks that could be applied to the values passed to the function. 1 2
Show mark scheme

7 [4 marks]

Calculate average AND final output statement(s) outside the loop

7(a)

 LENGTH(InString)  RIGHT(InString, InStringLen – Start + 1)  LEFT(MidString, Num) // alternative solution for LEFT() then RIGHT()  LEFT(InString, Start + Num - 1)  RIGHT(MidString, Num)

7(b) [5 marks]

and/or are >= 1 // positive Start Num Length of is "sufficient" for required operation InString

Q8
May/Jun 2022 Paper 2 v2

A program allows a user to save passwords used to log in to websites. A stored password is then inserted automatically when the user logs in to the corresponding website.

A global 2D array Secret of type STRING stores the passwords together with the website domain name where they are used. Secret contains 1000 elements organised as 500 rows by 2 columns.

Unused elements contain the empty string ( "" ). These may occur anywhere in the array.

Note:

part of the array is:
Array element Value
Secret[27, 1] "thiswebsite.com"
Secret[27, 2] ""
Secret[28, 1] "thatwebsite.com"
Secret[28, 2] ""
  • For security, the passwords are stored in an encrypted form, shown as "  " in the example.

  • The passwords cannot be used without being decrypted.

  • You may assume that the encrypted form of a password will NOT be an empty string.

The programmer has started to define program modules as follows:

Module Description
Exists()
Takes two parameters:


○ a string


○ a character

Performs a case-sensitive search for the character in the string

ReturnsTRUE if the character occurs in the string, otherwise
returnsFALSE
Encrypt()
Takes a password as a parameter of type string

Returns the encrypted form of the password as a string
Decrypt()
Takes an encrypted password as a parameter of type string

Returns the decrypted form of the password as a string

Note: in a case-sensitive comparison, 'a' is not the same as 'A'.

(a) Write pseudocode for the module Exists() . 5 marks

(b) A new module SearchDuplicates() will: 8 marks

  • search for the first password that occurs more than once in the array and output a message each time a duplicate is found. For example, if the same password was used for the three websites ThisWebsite.com, website27.net and websiteZ99.org, then the following messages will be output:
        "Password for ThisWebsite.com also used for website27.net"
        "Password for ThisWebsite.com also used for websiteZ99.org"
  • end once all messages have been output.

The module will output a message if no duplicates are found. For example:

        "No duplicate passwords found"

Write efficient pseudocode for the module SearchDuplicates() . Encrypt() and Decrypt() functions have been written.

Note : It is necessary to decrypt each password before checking its value.

(c) A password has a fixed format, consisting of three groups of four alphanumeric characters, separated by the hyphen character '-'. 6 marks

An example of a password is:

"FxAf-3haV-Tq49"

Each password must:

  • be 14 characters long

  • be organised as three groups of four alphanumeric characters. The groups are separated by hyphen characters

  • not include any duplicated characters, except for the hyphen characters.

An algorithm is needed for a new function GeneratePassword(), which will generate and return a password in this format.

Assume that the following modules have already been written:

Module Description
Exists()
Takes two parameters:


○ a string


○ a character

Performs a case-sensitive search for the character in the
string

ReturnsTRUE if the character occurs in the string, otherwise
returnsFALSE
RandomChar()
Generates a single random character from within one of the
following ranges:


○ 'a' to 'z'


○ 'A' to 'Z'


○ '0' to '9'

Returns the character

Note: in a case-sensitive comparison, 'a' is not the same as 'A'.

Describe the algorithm for GeneratePassword() .

Do not use pseudocode statements in your answer.

A program allows a user to save passwords used to log in to websites. A stored password is then inserted automatically when the user logs in to the corresponding website. A global 2D array `Secret` of type `STRING` stores the passwords together with the website domain name where they are used. `Secret` contains 1000 elements organised as 500 rows by 2 columns. Unused elements contain the empty string ( `""` ). These may occur anywhere in the array. Note: |part of the array is:|| |---|---| |**Array element**|**Value**| |`Secret[27, 1]`|"thiswebsite.com"| |`Secret[27, 2]`|""| |`Secret[28, 1]`|"thatwebsite.com"| |`Secret[28, 2]`|""| - For security, the passwords are stored in an encrypted form, shown as `"`  `"` in the example. - The passwords cannot be used without being decrypted. - You may assume that the encrypted form of a password will **NOT** be an empty string. The programmer has started to define program modules as follows: |Module|Description| |---|---| |`Exists()`|• <br>Takes two parameters:<br> <br> <br>○ a string<br> <br> <br>○ a character<br>• <br>Performs a case-sensitive search for the character in the string<br>• <br>Returns`TRUE` if the character occurs in the string, otherwise<br>returns`FALSE`| |`Encrypt()`|• <br>Takes a password as a parameter of type string<br>• <br>Returns the encrypted form of the password as a string| |`Decrypt()`|• <br>Takes an encrypted password as a parameter of type string<br>• <br>Returns the decrypted form of the password as a string| Note: in a case-sensitive comparison, 'a' is not the same as 'A'. ### (a) Write pseudocode for the module `Exists()` . <span class="part-marks">5 marks</span> ### (b) A new module `SearchDuplicates()` will: <span class="part-marks">8 marks</span> - search for the **first** password that occurs more than once in the array and output a message each time a duplicate is found. For example, if the same password was used for the three websites ThisWebsite.com, website27.net and websiteZ99.org, then the following messages will be output: ``` "Password for ThisWebsite.com also used for website27.net" "Password for ThisWebsite.com also used for websiteZ99.org" ``` - end once all messages have been output. The module will output a message if no duplicates are found. For example: ``` "No duplicate passwords found" ``` Write efficient pseudocode for the module `SearchDuplicates()` . `Encrypt()` and `Decrypt()` functions have been written. **Note** : It is necessary to decrypt each password before checking its value. ### (c) A password has a fixed format, consisting of **three groups of four** alphanumeric characters, separated by the hyphen character '-'. <span class="part-marks">6 marks</span> An example of a password is: "FxAf-3haV-Tq49" Each password must: - be 14 characters long - be organised as three groups of four alphanumeric characters. The groups are separated by hyphen characters - not include any duplicated characters, except for the hyphen characters. An algorithm is needed for a new function `GeneratePassword()`, which will generate and return a password in this format. Assume that the following modules have already been written: |Module|Description| |---|---| |`Exists()`|• <br>Takes two parameters:<br> <br> <br>○ a string<br> <br> <br>○ a character<br>• <br>Performs a case-sensitive search for the character in the<br>string<br>• <br>Returns`TRUE` if the character occurs in the string, otherwise<br>returns`FALSE`| |`RandomChar()`|• <br>Generates a single random character from within one of the<br>following ranges:<br> <br> <br>○ 'a' to 'z'<br> <br> <br>○ 'A' to 'Z'<br> <br> <br>○ '0' to '9'<br>• <br>Returns the character| Note: in a case-sensitive comparison, 'a' is not the same as 'A'. Describe the algorithm for `GeneratePassword()` . Do **not** use pseudocode statements in your answer.
Show mark scheme

8(a)

 FALSE  1  TRUE  Index + 1

8(b) [6 marks]

 FALSE  1  Secret[IndexA, 2]  Decrypt(ThisValue)  IndexA + 1 TO 500 //  TRUE  IndexA + 1 Max 8 : (Any) conditional loop... ... from 1 to 499 while (attempt at) no duplicate Skip unused password Use and assign return value to Decrypt() ThisPassword Inner loop from outer loop index + 1 to 500 searching for duplicates Compare with subsequent passwords ( after use of ThisPassword ) Decrypt() If match found, set outer loop termination and attempt an Output message giving duplicate Output 'No duplicate passwords found' message if no duplicates found after the loop

Q9
May/Jun 2022 Paper 2 v3

A program allows a user to save passwords used to log in to websites. A stored password is then inserted automatically when the user logs in to the corresponding website.

A student is developing a program to generate a strong password. The password will be of a fixed format, consisting of three groups of four alphanumeric characters, separated by the hyphen character '-'.

An example of a password is: "FxAf-3hzV-Aq49"

A valid password:

  • must be 14 characters long

  • must be organised as three groups of four alphanumeric characters. The groups are separated by hyphen characters

  • may include duplicated characters, provided these appear in different groups.

The programmer has started to define program modules as follows:

Module Description
RandomChar() • Generates a single random character from within one of the following
ranges:
○ 'a' to 'z'
○ 'A' to 'Z'
○ '0' to '9'
• Returns the character
Exists() • Takes two parameters:
○ a string
○ a character
• Performs a case-sensitive search for the character in the string
• ReturnsTRUE if the character occurs in the string, otherwise returns
FALSE
Generate() • Generates a valid password
• UsesRandomChar() andExists()
• Returns the password

Note: in a case-sensitive comparison, 'a' is not the same as 'A'.

(a) Write pseudocode for the module Generate() . 7 marks

(b) A global 2D array Secret of type STRING stores the passwords together with the website domain name where they are used. Secret contains 1000 elements organised as 500 rows by 2 columns. 6 marks

Unused elements contain the empty string ( "" ). These may occur anywhere in the array.

An example of part of the array is:

Array element Value
Secret[27, 1] "www.thiswebsite.com"
Secret[27, 2] "●●●●●●●●●●●●"
Secret[28, 1] "www.thatwebsite.com"
Secret[28, 2] "●●●●●●●●●●●●"

Note:

  • For security, the passwords are stored in an encrypted form, shown as "●●●●●●●●●●●●" in the example.

  • The passwords cannot be used without being decrypted.

  • You may assume that the encrypted form of a password will not be an empty string.

Additional modules are defined as follows:

Module Description
Encrypt() • Takes a password as a string
• Returns the encrypted form of the password as a string
Decrypt() • Takes an encrypted password as a string
• Returns the decrypted form of the password as a string
FindPassword() • Takes a website domain name as a string
• Searches for the website domain name in the arraySecret
• If the website domain name is found, the decrypted password is
returned
• If the website domain name is not found, an empty string is
returned
AddPassword() • Takes two parameters as strings: a website domain name and a
password
• Searches for the website domain name in the arraySecret and
if not found, adds the website domain name and the encrypted
password to the array
• ReturnsTRUE if the website domain name and encrypted
password are added to the array, otherwise returnsFALSE

The first three modules have been written.

Write pseudocode for the module AddPassword() .

(c) The content of the array Secret is to be stored in a text file for backup. 3 marks

It must be possible to read the data back from the file and extract the website domain name and the encrypted password.

Both the website domain name and encrypted password are stored in the array as strings of characters.

The encrypted password may contain any character from the character set used and the length of both the encrypted password and the website domain name is variable.

Explain how a single line of the text file can be used to store the website domain name and the encrypted password.

A program allows a user to save passwords used to log in to websites. A stored password is then inserted automatically when the user logs in to the corresponding website. A student is developing a program to generate a strong password. The password will be of a fixed format, consisting of **three groups of four** alphanumeric characters, separated by the hyphen character '-'. An example of a password is: "FxAf-3hzV-Aq49" A valid password: - must be 14 characters long - must be organised as three groups of four alphanumeric characters. The groups are separated by hyphen characters - may include duplicated characters, **provided** these appear in different groups. The programmer has started to define program modules as follows: |Module|Description| |---|---| |`RandomChar()`|• Generates a single random character from within one of the following<br>ranges:<br> ○ 'a' to 'z'<br> ○ 'A' to 'Z'<br> ○ '0' to '9'<br>• Returns the character| |`Exists()`|• Takes two parameters:<br> ○ a string<br> ○ a character<br>• Performs a case-sensitive search for the character in the string<br>• Returns`TRUE` if the character occurs in the string, otherwise returns<br>`FALSE`| |`Generate()`|• Generates a valid password<br>• Uses`RandomChar()` and`Exists()`<br>• Returns the password| Note: in a case-sensitive comparison, 'a' is not the same as 'A'. ### (a) Write pseudocode for the module `Generate()` . <span class="part-marks">7 marks</span> ### (b) A global 2D array `Secret` of type `STRING` stores the passwords together with the website domain name where they are used. `Secret` contains 1000 elements organised as 500 rows by 2 columns. <span class="part-marks">6 marks</span> Unused elements contain the empty string ( `""` ). These may occur anywhere in the array. An example of part of the array is: |Array element|Value| |---|---| |`Secret[27, 1]`|`"www.thiswebsite.com"`| |`Secret[27, 2]`|"●●●●●●●●●●●●"| |`Secret[28, 1]`|`"www.thatwebsite.com"`| |`Secret[28, 2]`|"●●●●●●●●●●●●"| Note: - For security, the passwords are stored in an encrypted form, shown as "●●●●●●●●●●●●" in the example. - The passwords cannot be used without being decrypted. - You may assume that the encrypted form of a password will **not** be an empty string. Additional modules are defined as follows: |Module|Description| |---|---| |`Encrypt()`|• Takes a password as a string<br>• Returns the encrypted form of the password as a string| |`Decrypt()`|• Takes an encrypted password as a string<br>• Returns the decrypted form of the password as a string| |`FindPassword()`|• Takes a website domain name as a string<br>• Searches for the website domain name in the array`Secret`<br>• If the website domain name is found, the decrypted password is<br>returned<br>• If the website domain name is not found, an empty string is<br>returned| |`AddPassword()`|• Takes two parameters as strings: a website domain name and a<br>password<br>• Searches for the website domain name in the array`Secret` and<br>if not found, adds the website domain name and the encrypted<br>password to the array<br>• Returns`TRUE` if the website domain name and encrypted<br>password are added to the array, otherwise returns`FALSE`| The first three modules have been written. Write pseudocode for the module `AddPassword()` . ### (c) The content of the array `Secret` is to be stored in a text file for backup. <span class="part-marks">3 marks</span> It **must** be possible to read the data back from the file and extract the website domain name and the encrypted password. Both the website domain name and encrypted password are stored in the array as strings of characters. The encrypted password may contain any character from the character set used and the length of both the encrypted password and the website domain name is variable. Explain how a single line of the text file can be used to store the website domain name and the encrypted password.
Show mark scheme

9(a) [6 marks]

DECLARE Password, Group : STRING DECLARE NextChar : CHAR DECLARE ACount, BCount : INTEGER CONSTANT HYPHEN = '-'  Password ""  FOR ACount 1 TO 3  Group ""  FOR BCount 1 TO 4 REPEAT  NextChar RandomChar() UNTIL Exists(Group, NextChar) = FALSE  Group Group & NextChar NEXT BCount  Password Password & Group & HYPHEN NEXT ACount  Password LEFT(Password, 14) // remove final hyphen RETURN Password ENDFUNCTION Marks as follows to Max 7 : 1 Declaration and initialisation of as Password STRING 2 Outer loop for three groups / until password is complete // three group loops 3 Attempt to use of both and in a loop RandomChar() Exists() 4 (Inner) loop for 4 characters in a group // note every 4 chars in a loop 5 Conditional loop until char is unique 6 Concatenating unique character to in a loop Group 7 Concatenate / random character to in a loop Group Password 8 (Attempt to) insert hyphens between groups (or removing later) and Return Password FUNCTION AddPassword(Name, Password : STRING)

9(b)

RETURNS BOOLEAN DECLARE Index : INTEGER DECLARE Added : BOOLEAN  Added FALSE  Index 1 IF FindPassword(Name) = "" THEN // Domain name not in // array WHILE Added = FALSE AND Index <= 500 IF Secret[Index, 1] = "" THEN  Secret[Index, 1] Name  Secret[Index, 2] Encrypt(Password)  Added TRUE ELSE  Index Index + 1 ENDIF ENDWHILE ENDIF RETURN Added ENDFUNCTION Marks as follows: 1 Check that the website domain name isn't already in array using / linear search, otherwise: FindPassword() 2 (Conditional) loop while not added and not end of array 3 Check for unused element by testing value in column 1 in a loop 4 If unused, write parameter values to column 1 and 2 and set flag / variable 5 ...having used on the password Encrypt() 6 Return value (correctly in all cases) BOOLEAN

9(c) [3 marks]

One mark per point to Max 3 . Solution based on field length:  Convert the length of the website domain name (either field) …  … to a string of fixed length  Form a string by concatenate this string with the other two (and write as one line of the file) Solution based on use of separator character:  Select a (separator) character that cannot occur in the domain name (e.g. space)  Create a string from the domain name followed by the separator  ...Concatenate the encrypted password (and write as one line of the file)

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

Q5
Oct/Nov 2021 Paper 2 v2

A company has several departments. Each department stores the name, email address and the status of each employee in that department in its own text file. All text files have the same format.

Employee details are stored as three separate data strings on three consecutive lines of the file. An example of the first six lines of one of the files is as follows:

File line Comment
1 First employee name
2 First email address
3 First employee status
4 Second employee name
5 Second email address
6 Second employee status

A procedure MakeNewFile() will:

  • take three parameters as strings:

  • an existing file name

  • a new file name

  • a search status value

    • create a new text file using the new file name

    • write all employee details to the new file where the employee status is not equal to the search status value

    • count the number of sets of employee details that were in the original file

    • count the number of sets of employee details that were written to the new file

    • produce a summary output.

An example summary output is as follows:

    File Marketing contained 54 employee details
    52 employee sets of details were written to file NewMarketingList

(a) Write pseudocode for the procedure MakeNewFile() . 7 marks

(b) An alternative format could be used for storing the data.

A text file will still be used.

(i) Describe the alternative format. 1 mark

(ii) State one advantage and one disadvantage of the alternative format. 2 marks

Advantage

Disadvantage

A company has several departments. Each department stores the name, email address and the status of each employee in that department in its own text file. All text files have the same format. Employee details are stored as three separate data strings on three consecutive lines of the file. An example of the first six lines of one of the files is as follows: |File line|Comment| |---|---| |1|First employee name| |2|First email address| |3|First employee status| |4|Second employee name| |5|Second email address| |6|Second employee status| A procedure `MakeNewFile()` will: - take three parameters as strings: - an existing file name - a new file name - a search status value - create a new text file using the new file name - write all employee details to the new file where the employee status is **not** equal to the search status value - count the number of sets of employee details that were in the original file - count the number of sets of employee details that were written to the new file - produce a summary output. An example summary output is as follows: ``` File Marketing contained 54 employee details 52 employee sets of details were written to file NewMarketingList ``` ### (a) Write pseudocode for the procedure `MakeNewFile()` . <span class="part-marks">7 marks</span> ### (b) An alternative format could be used for storing the data. A text file will still be used. #### (i) Describe the alternative format. <span class="part-marks">1 mark</span> #### (ii) State **one** advantage **and** **one** disadvantage of the alternative format. <span class="part-marks">2 marks</span> Advantage Disadvantage
Show mark scheme

5(a)

PROCEDURE MakeNewFile(OldFile, NewFile, Status : STRING) DECLARE Line1, Line2, Line3 : STRING DECLARE NumCopied, NumRecs : INTEGER ← NumRecs 0 ← NumCopied 0 OPENFILE OldFile FOR READ OPENFILE NewFile FOR WRITE WHILE NOT EOF(OldFile) READFILE OldFile, Line1 READFILE OldFile, Line2 READFILE OldFile, Line3 ← NumRecs NumRecs + 1 IF Line3 <> Status THEN WRITEFILE NewFile, Line1 WRITEFILE NewFile, Line2 WRITEFILE NewFile, Line3 ← NumCopied NumCopied + 1 ENDIF ENDWHILE OUTPUT "File " , OldFile , " contained " , NumRecs ,__ " employee details" OUTPUT Numcopied , " employee sets of details were __ written to file", NewFile CLOSEFILE OldFile CLOSEFILE NewFile ENDPROCEDURE Mark as follows: 1 Procedure heading and ending, including parameters 2 for and for and subsequently OPEN OldFile READ NewFile WRITE both files CLOSE 3 Conditional loop until EOF(OldFile) 4 Read three lines from in a loop OldFile 5 Compare 3 line read with parameter and if not equal write rd Status 3 lines to in a loop NewFile 6 Count number of sets read and those written in a loop 7 Final output including both counts and file names with suitable text after a loop Note: MP6: Both counts must have been declared and initialised

5(b)(i) [2 marks]

Store all three items on one line

5(b)(ii) [7 marks]

One mark per point: Advantage: Fewer file operations required Disadvantage: Algorithm to combine / extract individual data items is more complex

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

Q3
May/Jun 2021 Paper 2 v1

(a) A concert venue uses a program to calculate admission prices and store information about ticket sales.

A number of arrays are used to store data. The computer is switched off overnight and data has to be input again at the start of each day before any tickets can be sold. This process is very time consuming.

(i) Explain how the program could use text files to speed up the process. 2 marks

(ii) State the characteristic of text files that allow them to be used as explained in part (a)(i) . 1 mark

(iii) Information about ticket sales will be stored as a booking. The booking requires the following data: 2 marks

  • name of person booking

  • number of people in the group (for example a family ticket or a school party)

  • event type.

Suggest how data relating to each booking may be stored in a text file.

(b) A procedure Preview() will: 5 marks

  • take the name of a text file as a parameter

  • output a warning message if the file is empty

  • otherwise output the first five lines from the file (or as many lines as there are in the file if this number is less than five).

Write pseudocode for the procedure Preview() .

### (a) A concert venue uses a program to calculate admission prices and store information about ticket sales. A number of arrays are used to store data. The computer is switched off overnight and data has to be input again at the start of each day before any tickets can be sold. This process is very time consuming. #### (i) Explain how the program could use text files to speed up the process. <span class="part-marks">2 marks</span> #### (ii) State the characteristic of text files that allow them to be used as explained in **part (a)(i)** . <span class="part-marks">1 mark</span> #### (iii) Information about ticket sales will be stored as a booking. The booking requires the following data: <span class="part-marks">2 marks</span> - name of person booking - number of people in the group (for example a family ticket or a school party) - event type. Suggest how data relating to each booking may be stored in a text file. ### (b) A procedure `Preview()` will: <span class="part-marks">5 marks</span> - take the name of a text file as a parameter - output a warning message if the file is empty - otherwise output the first five lines from the file (or as many lines as there are in the file if this number is less than five). Write pseudocode for the procedure `Preview()` .
Show mark scheme

3(a)(i) [1 mark]

One mark per bullet point: Data from the arrays is written to the files at the end of the day / before the • program is terminated / computer is switched off Data can then be read from the files at the start of the next day and written to • / stored in the arrays No need to (re-)enter the data manually // only need to enter data once • Note: Max 2 marks

3(a)(ii)

The data is retained when the program is terminated / after the computer is • switched off // data is stored permanently // non-volatile storage

3(a)(iii) [5 marks]

One mark per bullet point: Data items are combined to form a single string / saved as a single line in the • file Data items are separated by a special character // make each data item a • fixed length ALTERNATIVE: Convert all data items / 'number of people' to strings • Consecutive / each line stores a separate data item •

3(b)

PROCEDURE Preview (ThisFile : STRING) DECLARE LineNum : INTEGER DECLARE ThisLine : STRING OPENFILE ThisFile FOR READ IF EOF(ThisFile) THEN OUTPUT “Warning Message” ELSE ← LineNum 1 WHILE LineNum < 6 AND NOT EOF(ThisFile) READFILE Thisfile, ThisLine OUTPUT ThisLine ← LineNum LineNum + 1 ENDWHILE ENDIF CLOSEFILE ThisFile ENDPROCEDURE Marks as follows: 1 Procedure heading (including parameter) and ending 2 File and subsequently OPEN CLOSE 3 Check if file is empty and output a warning message if it is 4 Conditional Loop 5 Output line (including blank lines) and read next line in a loop

Q7
May/Jun 2021 Paper 2 v1

A program is needed to take a string containing a full name and produce a new string of initials.

Some words in the full name will be ignored. For example, "the", "and", "of", "for" and "to" may all be ignored.

Each letter of the abbreviated string must be upper case.

For example:
Full name Initials
Integrated Development Environment IDE
The American Standard Code for Information Interchange ASCII

The programmer has decided to use a global variable FNString of type STRING to store the full name.

It is assumed that:

  • words in the full name string are separated by a single space character

  • space characters will not occur at the beginning or the end of the full name string

  • the full name string contains at least one word.

The programmer has started to define program modules as follows:

Module Description
GetStart()
Called with anINTEGER as a parameter, representing the number of a
word inFNString.

Returns the character start position of that word inFNString or
returns–1 if that word does not exist

For example: ifFNString contains the string"hot and cold",
GetStart(3) returns9
GetWord()
Called with a parameter representing the position of the first character
of a word inFNString

Returns the word fromFNString

For example: ifFNString contains the string"hot and cold",
GetWord(9) returns"cold"

(a) Write pseudocode for the module GetStart() . 7 marks

(b) The programmer has decided to use a global ten-element 1D array IgnoreList of type STRING to store the ignored words. Unused elements contain the empty string ( "" ) and may occur anywhere in the array. 4 marks 5 marks

A new module AddWord() is needed as follows:

Module Description
AddWord()
Called with a parameter representing a word

Stores the word in an unused element of theIgnoreList array
and returnsTRUE

ReturnsFALSE if the array was already full or if the word was
already in the array

Write a detailed description of the algorithm for AddWord() . Do not include pseudocode statements in your answer.

As a reminder, the m module description of GetWord() is repeated:
Module Description
GetWord()
Called with a parameter representing the position of the first
character of a word inFNString

Returns the word fromFNString

For example: ifFNString contains the string"hot and cold",
GetWord(9) returns"cold"

Write pseudocode for the module GetWord() .

A program is needed to take a string containing a full name and produce a new string of initials. Some words in the full name will be ignored. For example, "the", "and", "of", "for" and "to" may all be ignored. Each letter of the abbreviated string must be upper case. |For example:|| |---|---| |**Full name**|**Initials**| |Integrated Development Environment|IDE| |The American Standard Code for Information Interchange|ASCII| The programmer has decided to use a global variable `FNString` of type `STRING` to store the full name. It is assumed that: - words in the full name string are separated by a single space character - space characters will not occur at the beginning or the end of the full name string - the full name string contains at least one word. The programmer has started to define program modules as follows: |Module|Description| |---|---| |`GetStart()`|• <br>Called with an`INTEGER` as a parameter, representing the number of a<br>word in`FNString`. <br>• <br>Returns the character start position of that word in`FNString` or<br>returns`–1` if that word does not exist<br>• <br>For example: if`FNString` contains the string`"hot and cold"`, <br>`GetStart(3)` returns`9`| |`GetWord()`|• <br>Called with a parameter representing the position of the first character<br>of a word in`FNString`<br>• <br>Returns the word from`FNString`<br>• <br>For example: if`FNString` contains the string`"hot and cold"`, <br>`GetWord(9)` returns`"cold"`| ### (a) Write pseudocode for the module `GetStart()` . <span class="part-marks">7 marks</span> ### (b) The programmer has decided to use a global ten-element 1D array `IgnoreList` of type `STRING` to store the ignored words. Unused elements contain the empty string ( `""` ) and may occur anywhere in the array. <span class="part-marks">4 marks</span> <span class="part-marks">5 marks</span> A new module `AddWord()` is needed as follows: |Module|Description| |---|---| |`AddWord()`|• <br>Called with a parameter representing a word<br>• <br>Stores the word in an unused element of the`IgnoreList` array<br>and returns`TRUE`<br>• <br>Returns`FALSE` if the array was already full or if the word was<br>already in the array| Write a detailed description of the algorithm for `AddWord()` . Do **not** include pseudocode statements in your answer. |As a reminder, the m|module description of GetWord() is repeated:| |---|---| |**Module**|**Description**| |`GetWord()`|• <br>Called with a parameter representing the position of the first<br>character of a word in`FNString`<br>• <br>Returns the word from`FNString`<br>• <br>For example: if`FNString` contains the string`"hot and cold"`, <br>`GetWord(9)` returns`"cold"`| Write pseudocode for the module `GetWord()` .
Show mark scheme

7(a) [4 marks]

FUNCTION GetStart (WordNum : INTEGER) RETURNS INTEGER DECLARE Index, ThisPos, NumFound : INTEGER DECLARE ThisChar : Char CONSTANT SPACECHAR = ' ' ← Index -1 ← Numfound 0 ← ThisPos 1 IF WordNum = 1 THEN // if looking for word 1... ← Index 1 // Word 1 always starts at index // position 1 ELSE // Otherwise start counting spaces... WHILE ThisPos <= LENGTH(FNString) AND Index = -1 ← ThisChar MID(FNString, ThisPos, 1) IF ThisChar = SPACECHAR THEN ← NumFound NumFound + 1 IF NumFound = WordNum - 1 THEN ← Index ThisPos + 1 // the start of the // required word ENDIF ENDIF ← ThisPos ThisPos + 1 ENDWHILE ENDIF RETURN Index ENDFUNCTION 1 mark for each of the following: 1 Function heading, including return type and function end 2 Loop counting spaces until word found or end of FNString 3 extract a character from in a loop FNString 4 compare with and increment count if equal in a loop SPACECHAR 5 compare count with (depending on initialisation WordNum - 1 value) in a loop 6 if equal then set flag or to in a loop Index ThisPos + 1 7 Return Index (correctly in all cases / following a reasonable attempt) 8 Works for special case when looking for word 1 Note: Max 7 marks

7(b) [5 marks]

Marks awarded for any reference to each of the following steps of the algorithm: 1 Mention of variable for use as array index 2 Use of a loop (to check through the array) 3 If word is the same as the current array element then return FALSE set flag 4 If word not already in array, loop to find unused element (second loop) 5 Store word in unused element and return , otherwise return TRUE FALSE VARIATION: 1 Mention of variable for use as array index 2 Use of a loop (to check through the array) 3 Save index of (first) unused element found 4 If word is the same as the current array element then return FALSE set flag 5 If word not already in array and unused element available, store word in unused element and return otherwise return TRUE FALSE Note: Max 4 marks

7(c)

The ‘length and substring’ solution: FUNCTION GetWord (Index : INTEGER) RETURNS STRING DECLARE Done : BOOLEAN DECLARE ThisChar : CHAR DECLARE Index, NextPos : INTEGER CONSTANT SPACECHAR = ' ' ← Done FALSE ← NextPos Index // must be at least one character in // the required word REPEAT ← ThisChar MID(FNString, NextPos, 1) IF ThisChar = SPACECHAR OR NextPos = LENGTH(FNString) THEN ← Done TRUE ELSE ← NextPos NextPos + 1 ENDIF UNTIL Done = TRUE IF NextPos = LENGTH(FNString) THEN ← NextPos NextPos - 1 // special case when last word ENDIF RETURN MID(FNString, Index, NextPos - Index) ENDFUNCTION 1 mark for each of the following: 1 Conditional loop 2 ...extract char from and compare with in a FNString SPACECHAR loop 3 .. increment count if word continues 4 Exit loop when encountered or when end of SPACECHAR FNString reached 5 Apply substring function and Return

Q8
May/Jun 2021 Paper 2 v2

A program is needed to take a string containing a full name and to produce a new string of initials.

Some words in the full name will be ignored. For example, “the”, “and”, “of”, “for” and “to” may all be ignored.

Each letter of the new string must be upper case.

For example:
Full name Initials
Integrated Development Environment IDE
The American Standard Code for Information Interchange ASCII

The programmer has decided to use the following global variables:

  • a ten element 1D array IgnoreList of type STRING to store the ignored words

  • a string FNString to store the full name string.

Assume that:

  • each alphabetic character in the full name string may be either upper or lower case

  • the full name string contains at least one word.

The programmer has started to define program modules as follows:

Module Description
GetStart() • Called with anINTEGER as its parameter, representing the number of
a word inFNString
• Returns the character start position of that word inFNString or
returns-1 if that word does not exist
• For example:GetStart(3) applied to"hot and cold" returns9
GetWord()
• Called with the position of the first character of a word inFNString
as its parameter
• Returns the word fromFNString
• For example: ifFNString contains the string"hot and cold",
GetWord(9) returns"cold"
IgnoreWord() • Called with aSTRING parameter representing a word
• Searches for the word in theIgnoreList array
• ReturnsTRUE if the word is found, otherwise returnsFALSE
GetInitials() • Processes the sequence of words in the full name one word at a time
• CallsGetStart(), GetWord() andIgnoreWord() to process
each word to form the new string
• Outputs the new string

(a) Write pseudocode for the module IgnoreWord() . 5 marks

(b) Write pseudocode for the module GetInitials() . 8 marks

A program is needed to take a string containing a full name and to produce a new string of initials. Some words in the full name will be ignored. For example, “the”, “and”, “of”, “for” and “to” may all be ignored. Each letter of the new string must be upper case. |For example:|| |---|---| |**Full name**|**Initials**| |Integrated Development Environment|IDE| |The American Standard Code for Information Interchange|ASCII| The programmer has decided to use the following global variables: - a ten element 1D array `IgnoreList` of type `STRING` to store the ignored words - a string `FNString` to store the full name string. Assume that: - each alphabetic character in the full name string may be either upper or lower case - the full name string contains at least one word. The programmer has started to define program modules as follows: |Module|Description| |---|---| |`GetStart()`|• Called with an`INTEGER` as its parameter, representing the number of<br>a word in`FNString`<br>• Returns the character start position of that word in`FNString` or<br>returns`-1` if that word does not exist<br>• For example:`GetStart(3)` applied to`"hot and cold"` returns`9`| |`GetWord()`|<br>• Called with the position of the first character of a word in`FNString`<br>as its parameter<br>• Returns the word from`FNString`<br>• For example: if`FNString` contains the string`"hot and cold"`, <br>`GetWord(9)` returns`"cold"`| |`IgnoreWord()`|• Called with a`STRING` parameter representing a word<br>• Searches for the word in the`IgnoreList` array<br>• Returns`TRUE` if the word is found, otherwise returns`FALSE`| |`GetInitials()`|• Processes the sequence of words in the full name one word at a time<br>• Calls`GetStart()`, `GetWord()` and`IgnoreWord()` to process<br>each word to form the new string<br>• Outputs the new string| ### (a) Write pseudocode for the module `IgnoreWord()` . <span class="part-marks">5 marks</span> ### (b) Write pseudocode for the module `GetInitials()` . <span class="part-marks">8 marks</span>
Show mark scheme

8(a) [8 marks]

FUNCTION IgnoreWord (ThisWord : STRING) RETURNS BOOLEAN DECLARE Found : BOOLEAN DECLARE Index : INTEGER ← Found False ← Index 1 ← ThisWord TO_LOWER(ThisWord) REPEAT IF TO_LOWER(IgnoreList[Index]) = ThisWord THEN ← Found TRUE ENDIF ← Index Index + 1 UNTIL Found = TRUE OR Index > 10 RETURN Found ENDFUNCTION 1 mark for each of the following: 1 Loop through array elements 2 Convert both strings to same case 3 Compare array element with parameter in a loop 4 Set a flag (or similar) if match found (after reasonable attempt at MP3) in a loop 5 Return or in all cases TRUE FALSE Note: Max 4 if function declaration incorrect

8(b)

Procedure GetInitials() DECLARE NewString, NextWord : STRING DECLARE ThisWordNum, Index : INTEGER ← ThisWordNum 0 ← NewString "" REPEAT ← ThisWordNum ThisWordNum + 1 ← Index GetStart(ThisWordNum) IF Index <> -1 THEN //if there is ThisWordNum ← NextWord GetWord(Index) IF IgnoreWord(NextWord) = FALSE THEN ← NewString NewString & UCASE(LEFT(NextWord, 1)) ENDIF ENDIF UNTIL Index = -1 OUTPUT NewString ENDPROCEDURE 1 mark for each of the following: 1 Declare and initialise to empty string NewString 2 Conditional loop to pick out all words from FNString 3 Evaluate result of in a loop GetStart() 4 Test result <> -1 and if not: 5 Assign result of to a variable in a loop GetWord() 6 Test result of in a loop IgnoreWord() 7 If not ignored, add the next initial letter to in a NewString loop 8 Increment (must have been initialised) in a loop ThisWordNum 9 Output (must be all upper case) outside loop NewString Note: Max 8 marks

Q3
May/Jun 2021 Paper 2 v3

(a) A concert venue uses a program to calculate admission prices and store information about ticket sales.

A number of arrays are used to store data. The computer is switched off overnight and data has to be input again at the start of each day before any tickets can be sold. This process is very time consuming.

(i) Explain how the program could use text files to speed up the process. 2 marks

(ii) State the characteristic of text files that allow them to be used as explained in part (a)(i) . 1 mark

(iii) Information about ticket sales will be stored as a booking. The booking requires the following data: 2 marks

  • name of person booking

  • number of people in the group (for example a family ticket or a school party)

  • event type.

Suggest how data relating to each booking may be stored in a text file.

(b) A procedure Preview() will: 5 marks

  • take the name of a text file as a parameter

  • output a warning message if the file is empty

  • otherwise output the first five lines from the file (or as many lines as there are in the file if this number is less than five).

Write pseudocode for the procedure Preview() .

### (a) A concert venue uses a program to calculate admission prices and store information about ticket sales. A number of arrays are used to store data. The computer is switched off overnight and data has to be input again at the start of each day before any tickets can be sold. This process is very time consuming. #### (i) Explain how the program could use text files to speed up the process. <span class="part-marks">2 marks</span> #### (ii) State the characteristic of text files that allow them to be used as explained in **part (a)(i)** . <span class="part-marks">1 mark</span> #### (iii) Information about ticket sales will be stored as a booking. The booking requires the following data: <span class="part-marks">2 marks</span> - name of person booking - number of people in the group (for example a family ticket or a school party) - event type. Suggest how data relating to each booking may be stored in a text file. ### (b) A procedure `Preview()` will: <span class="part-marks">5 marks</span> - take the name of a text file as a parameter - output a warning message if the file is empty - otherwise output the first five lines from the file (or as many lines as there are in the file if this number is less than five). Write pseudocode for the procedure `Preview()` .
Show mark scheme

3(a)(i) [1 mark]

One mark per bullet point: Data from the arrays is written to the files at the end of the day / before the • program is terminated / computer is switched off Data can then be read from the files at the start of the next day and written to • / stored in the arrays No need to (re-)enter the data manually // only need to enter data once • Note: Max 2 marks

3(a)(ii)

The data is retained when the program is terminated / after the computer is • switched off // data is stored permanently // non-volatile storage

3(a)(iii) [5 marks]

One mark per bullet point: Data items are combined to form a single string / saved as a single line in the • file Data items are separated by a special character // make each data item a • fixed length ALTERNATIVE: Convert all data items / 'number of people' to strings • Consecutive / each line stores a separate data item •

3(b)

PROCEDURE Preview (ThisFile : STRING) DECLARE LineNum : INTEGER DECLARE ThisLine : STRING OPENFILE ThisFile FOR READ IF EOF(ThisFile) THEN OUTPUT “Warning Message” ELSE ← LineNum 1 WHILE LineNum < 6 AND NOT EOF(ThisFile) READFILE Thisfile, ThisLine OUTPUT ThisLine ← LineNum LineNum + 1 ENDWHILE ENDIF CLOSEFILE ThisFile ENDPROCEDURE Marks as follows: 1 Procedure heading (including parameter) and ending 2 File and subsequently OPEN CLOSE 3 Check if file is empty and output a warning message if it is 4 Conditional Loop 5 Output line (including blank lines) and read next line in a loop

Q7
May/Jun 2021 Paper 2 v3

A program is needed to take a string containing a full name and produce a new string of initials.

Some words in the full name will be ignored. For example, "the", "and", "of", "for" and "to" may all be ignored.

Each letter of the abbreviated string must be upper case.

For example:
Full name Initials
Integrated Development Environment IDE
The American Standard Code for Information Interchange ASCII

The programmer has decided to use a global variable FNString of type STRING to store the full name.

It is assumed that:

  • words in the full name string are separated by a single space character

  • space characters will not occur at the beginning or the end of the full name string

  • the full name string contains at least one word.

The programmer has started to define program modules as follows:

Module Description
GetStart()
Called with anINTEGER as a parameter, representing the number of a
word inFNString.

Returns the character start position of that word inFNString or
returns–1 if that word does not exist

For example: ifFNString contains the string"hot and cold",
GetStart(3) returns9
GetWord()
Called with a parameter representing the position of the first character
of a word inFNString

Returns the word fromFNString

For example: ifFNString contains the string"hot and cold",
GetWord(9) returns"cold"

(a) Write pseudocode for the module GetStart() . 7 marks

(b) The programmer has decided to use a global ten-element 1D array IgnoreList of type STRING to store the ignored words. Unused elements contain the empty string ( "" ) and may occur anywhere in the array. 4 marks 5 marks

A new module AddWord() is needed as follows:

Module Description
AddWord()
Called with a parameter representing a word

Stores the word in an unused element of theIgnoreList array
and returnsTRUE

ReturnsFALSE if the array was already full or if the word was
already in the array

Write a detailed description of the algorithm for AddWord() . Do not include pseudocode statements in your answer.

As a reminder, the m module description of GetWord() is repeated:
Module Description
GetWord()
Called with a parameter representing the position of the first
character of a word inFNString

Returns the word fromFNString

For example: ifFNString contains the string"hot and cold",
GetWord(9) returns"cold"

Write pseudocode for the module GetWord() .

A program is needed to take a string containing a full name and produce a new string of initials. Some words in the full name will be ignored. For example, "the", "and", "of", "for" and "to" may all be ignored. Each letter of the abbreviated string must be upper case. |For example:|| |---|---| |**Full name**|**Initials**| |Integrated Development Environment|IDE| |The American Standard Code for Information Interchange|ASCII| The programmer has decided to use a global variable `FNString` of type `STRING` to store the full name. It is assumed that: - words in the full name string are separated by a single space character - space characters will not occur at the beginning or the end of the full name string - the full name string contains at least one word. The programmer has started to define program modules as follows: |Module|Description| |---|---| |`GetStart()`|• <br>Called with an`INTEGER` as a parameter, representing the number of a<br>word in`FNString`. <br>• <br>Returns the character start position of that word in`FNString` or<br>returns`–1` if that word does not exist<br>• <br>For example: if`FNString` contains the string`"hot and cold"`, <br>`GetStart(3)` returns`9`| |`GetWord()`|• <br>Called with a parameter representing the position of the first character<br>of a word in`FNString`<br>• <br>Returns the word from`FNString`<br>• <br>For example: if`FNString` contains the string`"hot and cold"`, <br>`GetWord(9)` returns`"cold"`| ### (a) Write pseudocode for the module `GetStart()` . <span class="part-marks">7 marks</span> ### (b) The programmer has decided to use a global ten-element 1D array `IgnoreList` of type `STRING` to store the ignored words. Unused elements contain the empty string ( `""` ) and may occur anywhere in the array. <span class="part-marks">4 marks</span> <span class="part-marks">5 marks</span> A new module `AddWord()` is needed as follows: |Module|Description| |---|---| |`AddWord()`|• <br>Called with a parameter representing a word<br>• <br>Stores the word in an unused element of the`IgnoreList` array<br>and returns`TRUE`<br>• <br>Returns`FALSE` if the array was already full or if the word was<br>already in the array| Write a detailed description of the algorithm for `AddWord()` . Do **not** include pseudocode statements in your answer. |As a reminder, the m|module description of GetWord() is repeated:| |---|---| |**Module**|**Description**| |`GetWord()`|• <br>Called with a parameter representing the position of the first<br>character of a word in`FNString`<br>• <br>Returns the word from`FNString`<br>• <br>For example: if`FNString` contains the string`"hot and cold"`, <br>`GetWord(9)` returns`"cold"`| Write pseudocode for the module `GetWord()` .
Show mark scheme

7(a) [4 marks]

FUNCTION GetStart (WordNum : INTEGER) RETURNS INTEGER DECLARE Index, ThisPos, NumFound : INTEGER DECLARE ThisChar : Char CONSTANT SPACECHAR = ' ' ← Index -1 ← Numfound 0 ← ThisPos 1 IF WordNum = 1 THEN // if looking for word 1... ← Index 1 // Word 1 always starts at index // position 1 ELSE // Otherwise start counting spaces... WHILE ThisPos <= LENGTH(FNString) AND Index = -1 ← ThisChar MID(FNString, ThisPos, 1) IF ThisChar = SPACECHAR THEN ← NumFound NumFound + 1 IF NumFound = WordNum - 1 THEN ← Index ThisPos + 1 // the start of the // required word ENDIF ENDIF ← ThisPos ThisPos + 1 ENDWHILE ENDIF RETURN Index ENDFUNCTION 1 mark for each of the following: 1 Function heading, including return type and function end 2 Loop counting spaces until word found or end of FNString 3 extract a character from in a loop FNString 4 compare with and increment count if equal in a loop SPACECHAR 5 compare count with (depending on initialisation WordNum - 1 value) in a loop 6 if equal then set flag or to in a loop Index ThisPos + 1 7 Return Index (correctly in all cases / following a reasonable attempt) 8 Works for special case when looking for word 1 Note: Max 7 marks

7(b) [5 marks]

Marks awarded for any reference to each of the following steps of the algorithm: 1 Mention of variable for use as array index 2 Use of a loop (to check through the array) 3 If word is the same as the current array element then return FALSE set flag 4 If word not already in array, loop to find unused element (second loop) 5 Store word in unused element and return , otherwise return TRUE FALSE VARIATION: 1 Mention of variable for use as array index 2 Use of a loop (to check through the array) 3 Save index of (first) unused element found 4 If word is the same as the current array element then return FALSE set flag 5 If word not already in array and unused element available, store word in unused element and return otherwise return TRUE FALSE Note: Max 4 marks

7(c)

The ‘length and substring’ solution: FUNCTION GetWord (Index : INTEGER) RETURNS STRING DECLARE Done : BOOLEAN DECLARE ThisChar : CHAR DECLARE Index, NextPos : INTEGER CONSTANT SPACECHAR = ' ' ← Done FALSE ← NextPos Index // must be at least one character in // the required word REPEAT ← ThisChar MID(FNString, NextPos, 1) IF ThisChar = SPACECHAR OR NextPos = LENGTH(FNString) THEN ← Done TRUE ELSE ← NextPos NextPos + 1 ENDIF UNTIL Done = TRUE IF NextPos = LENGTH(FNString) THEN ← NextPos NextPos - 1 // special case when last word ENDIF RETURN MID(FNString, Index, NextPos - Index) ENDFUNCTION 1 mark for each of the following: 1 Conditional loop 2 ...extract char from and compare with in a FNString SPACECHAR loop 3 .. increment count if word continues 4 Exit loop when encountered or when end of SPACECHAR FNString reached 5 Apply substring function and Return