Skip to content

11.1 Programming Basics

AS Level · 52 questions found

  • Implement pseudocode from a flowchart or structured English
  • Declare/initialise constants and variables; assign values
  • Arithmetic and logical expressions; keyboard input and console output
  • Use built-in functions and library routines; string manipulation
Q1
Oct/Nov 2025 Paper 2 v1

A program is being developed to meet a particular customer requirement.

(a) The program contains these variables: 4 marks

Variable Data type
MyChar CHAR
MyString STRING
MyInt INTEGER
MyDOB DATE

Complete the table by filling in the gaps using functions and/or operators from the insert.

Each expression must be valid.

(b) Different test methods will be used at different stages of the program development. 3 marks

Complete the table by identifying the test method that matches the test description.

The first row has been completed for you.

Test description Test method
carried out as soon as a program module has been coded alpha
carried out as program modules are being combined
completed by the developers without referring to the code
completed by the customer

(c) During the alpha testing stage, an Integrated Development Environment (IDE) is used to help locate an error that has been identified. The IDE report window feature is used to examine the values assigned to variables. 3 marks

Explain how two other IDE features are used together with the report window feature to help locate the error.

A program is being developed to meet a particular customer requirement. ### (a) The program contains these variables: <span class="part-marks">4 marks</span> |Variable|Data type| |---|---| |MyChar|CHAR| |MyString|STRING| |MyInt|INTEGER| |MyDOB|DATE| Complete the table by filling in the gaps using functions and/or operators from the insert. Each expression must be valid. ### (b) Different test methods will be used at different stages of the program development. <span class="part-marks">3 marks</span> Complete the table by identifying the test method that matches the test description. The first row has been completed for you. |Test description|Test method| |---|---| |carried out as soon as a program module has been coded|alpha| |carried out as program modules are being combined|| |completed by the developers without referring to the code|| |completed by the customer|| ![](../images/w25_21_q1_fig1.png) ### (c) During the alpha testing stage, an Integrated Development Environment (IDE) is used to help locate an error that has been identified. The IDE report window feature is used to examine the values assigned to variables. <span class="part-marks">3 marks</span> Explain how two other IDE features are used together with the report window feature to help locate the error.
Show mark scheme

1(a) [4 marks]

Expression  & MyString 'X' MyString  MID 1 / 2 / 3 / 4 , 1 MyChar ("ABCD", )  NUM_TO_STR ( DAY / MONTH / YEAR / DAYINDEX MyString (MyDOB))  INT LENGTH MyInt ( (MyString) / 2) One mark per row

1(b) [3 marks]

Test description Test method carried out as soon as a program module has been alpha coded carried out as program modules are being integration combined completed by the developers without referring to black-box the code completed by the customer acceptance / beta One mark per row (2 to 4)

1(c) [3 marks]

One mark per point: 1 reference to a breakpoint 2 reference to single stepping 3 Correct explanation of both e.g. to stop program execution at specific point / line / statement / instruction and to execute one line / statement / instruction at a time to (locate an/the error) One mark for each bulleted point

Q1
Oct/Nov 2025 Paper 2 v2

(a) The table contains pseudocode examples. 4 marks

Each example may contain statements that relate to one or more of:

  • selection

  • iteration (repetition)

  • subroutines (procedures or functions).

Complete the table by placing one or more ticks (‘3’) in each row.

Pseudocode example Selection Iteration Subroutine
IF Status = FALSE THEN
FOR Count
1 TO 20
CALL Reset(Count)
NEXT Count
ENDIF
OTHERWISE : Status
TRUE
WHILE AllDone() = TRUE
30 : NextChar
'X'

(b) Complete the table by giving the appropriate data type. 3 marks

Variable Example data value Data type
Result 5.42
MonthLetter "JFMAMJJASOND"
Birthday 15/11/2009

(c) Evaluate each expression in the table by using the data values shown in (b). 4 marks

Write ‘ERROR’ if the expression contains an error.

Expression Evaluates to
INT(Result) + 1 > 6
NUM_TO_STR(LENGTH(MonthLetter))
NUM_TO_STR(Result + "3.2")
MID(MonthLetter, MONTH(Birthday) — 2, 1)
### (a) The table contains pseudocode examples. <span class="part-marks">4 marks</span> Each example may contain statements that relate to one or more of: - selection - iteration (repetition) - subroutines (procedures or functions). Complete the table by placing one or more ticks (‘3’) in each row. |Pseudocode example|Selection|Iteration|Subroutine| |---|---|---|---| |IF Status = FALSE THEN<br> FOR Count<br> 1 TO 20<br> CALL Reset(Count)<br> NEXT Count<br>ENDIF|||| |OTHERWISE : Status<br> TRUE|||| |WHILE AllDone() = TRUE|||| |30 : NextChar<br> 'X'|||| ### (b) Complete the table by giving the appropriate data type. <span class="part-marks">3 marks</span> |Variable|Example data value|Data type| |---|---|---| |Result|5.42|| |MonthLetter|"JFMAMJJASOND"|| |Birthday|15/11/2009|| ### (c) Evaluate each expression in the table by using the data values shown in (b). <span class="part-marks">4 marks</span> Write ‘ERROR’ if the expression contains an error. |Expression|Evaluates to| |---|---| |INT(Result) + 1 > 6|| |NUM_TO_STR(LENGTH(MonthLetter))|| |NUM_TO_STR(Result + "3.2")|| |MID(MonthLetter, MONTH(Birthday) — 2, 1)||
Show mark scheme

1(a) [4 marks]

Pseudocode example Selection Iteration Subroutine IF Status = FALSE THEN     FOR Count 1 TO 20 CALL Reset(Count) NEXT Count ENDIF   OTHERWISE : Status TRUE WHILE AllDone() = TRUE     30 : NextChar 'X' One mark per row

1(b) [3 marks]

Variable Example data value Data type REAL Result 5.42 STRING MonthLetter "JFMAMJJASOND" DATE Birthday 15/11/2009 One mark per row

1(c) [4 marks]

Expression Evaluates to FALSE INT(Result) + 1 > 6 "12" NUM_TO_STR(LENGTH(MonthLetter)) NUM_TO_STR(Result + "3.2") ERROR MID(MonthLetter, MONTH(Birthday) — 2, 1) "S" One mark per row

Q1
May/Jun 2025 Paper 2 v1

A program is being developed to help the manager of a shop control the stock.

(a) An identifier table has been used during the design stage. 4 marks

Complete the identifier table:

Example value Explanation Variable name Data type
"Fruit" a category of stock
that is sold in the shop
20/02/2025 when an item was
sold
12.67 the cost of an item
TRUE to indicate if an item is
in stock

(b) A module Sales() is part of the stock control program. 5 marks

The table contains pseudocode extracts from the module Sales()

Each extract may include all or part of:

  • assignment

  • selection

  • iteration (repetition).

Complete the table by placing one or more ticks (✓) in each row:

Pseudocode extract Assignment Selection Iteration
Result
CalculateTotal()
WHILE IsClosed
REPEAT
INPUT Value
UNTIL Sales[4] > Value
IF Sales[Current] <= 150 THEN
Discount
TRUE
ENDIF
CASE OF Option
A program is being developed to help the manager of a shop control the stock. ### (a) An identifier table has been used during the design stage. <span class="part-marks">4 marks</span> Complete the identifier table: |Example value|Explanation|Variable name|Data type| |---|---|---|---| |"Fruit"|a category of stock<br>that is sold in the shop||| |20/02/2025|when an item was<br>sold||| |12.67|the cost of an item||| |TRUE|to indicate if an item is<br>in stock||| ### (b) A module Sales() is part of the stock control program. <span class="part-marks">5 marks</span> The table contains pseudocode extracts from the module Sales() Each extract may include all or part of: - assignment - selection - iteration (repetition). Complete the table by placing one or more ticks (✓) in each row: |Pseudocode extract|Assignment|Selection|Iteration| |---|---|---|---| |Result<br> CalculateTotal()|||| |WHILE IsClosed|||| |REPEAT<br> INPUT Value<br>UNTIL Sales[4] > Value|||| |IF Sales[Current] <= 150 THEN<br> Discount<br> TRUE<br>ENDIF|||| |CASE OF Option||||
Show mark scheme

1(a) [4 marks]

Example Explanation Variable name Data type value "Fruit" Category STRING a category of stock that is sold in the shop DateSold DATE when an item was sold 12.67 (Item)Cost/Price REAL the cost of an item TRUE (Item)InStock BOOLEAN to indicate if an item is in stock and data type

1(b) [5 marks]

Pseudocode extract Assignment Selection Iteration  ✓ CalculateTotal() ✓ ✓ ✓ ✓ ✓  TRUE ✓

1(c) [3 marks]

Breaking down a problem into sub problems In order to explain / understand the process/task of how a (stock control) can be managed in more detail Leading to the concept of the program designed as a series of modules / procedures / functions // or by example of different stock control modules Makes the program easier to test / debug if no mention of stock control

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

Q1
Oct/Nov 2024 Paper 2 v1

A program will calculate the tax payable based on the cost of an item.

Calculations will occur at many places in the program and these involve the use of one of three tax rates.

Tax rate values represent a percentage. For example, a tax rate value of 5.23 represents 5.23%. In this case, the tax payable on an item costing $100 would be $5.23.

Tax rate values are used at several places within the program. One example is given in pseudocode as follows:

HighRate ← FALSE CASE OF ItemCost <= 50 : TaxRate ← 3.75 // tax rate of 3.75% <= 200 : TaxRate ← 5.23 // tax rate of 5.23%

  • 200 : TaxRate ← 6.25 // tax rate of 6.25% HighRate ← TRUE ENDCASE TaxPayable ← ItemCost * TaxRate // tax payable

(a) The pseudocode contains a logical error. 2 marks

Identify the error and suggest a correction.

Error

Correction

(b) During the design of the program, tax rate values have been used wherever they are needed as shown in the pseudocode example above. Tax rates do not change while the program runs.

(i) Identify a more appropriate way of representing the tax rate values in the final program. 1 mark

(ii) Describe the benefits of your answer to part (b)(i) with reference to this program. 3 marks

A program will calculate the tax payable based on the cost of an item. Calculations will occur at many places in the program and these involve the use of one of three tax rates. Tax rate values represent a percentage. For example, a tax rate value of 5.23 represents 5.23%. In this case, the tax payable on an item costing $100 would be $5.23. Tax rate values are used at several places within the program. One example is given in pseudocode as follows: HighRate ← FALSE CASE OF ItemCost <= 50 : TaxRate ← 3.75 // tax rate of 3.75% <= 200 : TaxRate ← 5.23 // tax rate of 5.23% - 200 : TaxRate ← 6.25 // tax rate of 6.25% HighRate ← TRUE ENDCASE TaxPayable ← ItemCost * TaxRate // tax payable ### (a) The pseudocode contains a logical error. <span class="part-marks">2 marks</span> Identify the error and suggest a correction. Error Correction ### (b) During the design of the program, tax rate values have been used wherever they are needed as shown in the pseudocode example above. Tax rates do not change while the program runs. #### (i) Identify a more appropriate way of representing the tax rate values in the final program. <span class="part-marks">1 mark</span> #### (ii) Describe the benefits of your answer to part (b)(i) with reference to this program. <span class="part-marks">3 marks</span>
Show mark scheme

1(a) [2 marks]

One mark per point: Error: The calculation of TaxPayable is incorrect  Correction: TaxPayable (ItemCost * TaxRate) / 100

1(b)(i) [1 mark]

Use constants (to represent the tax rate values)

1(b)(ii) [3 marks]

One mark per bullet point (or equivalent to max 3): 1 Tax rates are entered once only 2 Avoids / Minimise (input) error(s) / changing the Tax rates accidentally // avoids different values for tax rates at different points in the program 3 When required, the constant value (representing a tax rate) is changed (once) // Easier to maintain / update the program (when the tax rates change) 4 Makes the program / code easier to understand

1(c) [2 marks]

One mark per row: Variable name Data type HighRate Boolean TaxPayable Real

1(d) [1 mark]

OTHERWISE

Q1
Oct/Nov 2024 Paper 2 v3

(a) The following table contains pseudocode examples. 4 marks

Each example may contain statements that relate to one or more of the following:

  • selection

  • iteration (repetition)

  • subroutine (procedure or function).

Complete the table by placing one or more ticks ('✓') in each row.

Pseudocode example Selection Iteration Subroutine
FOR Index~~←~~ 1 TO 3
IF Safe[Index] = TRUE THEN
Flap[Index]← 0
ENDIF
NEXT Index
CASE OF Compound(3)
REPEAT UNTIL AllDone() = TRUE
WHILE Result[3] <> FALSE

(b) Complete the table by giving the appropriate data type in each case. 3 marks

Variable Example data value Data type
Available TRUE
Received "18/04/2021"
Index 100

(c) Evaluate each expression in the table by using the data values shown in part (b). 3 marks

Write ‘ERROR’ if the expression contains an error.

Expression Evaluates to
Available AND NOT(Index > 100)
Index MOD 30
NUM_TO_STR(Index + "33")
### (a) The following table contains pseudocode examples. <span class="part-marks">4 marks</span> Each example may contain statements that relate to one or more of the following: - selection - iteration (repetition) - subroutine (procedure or function). Complete the table by placing one or more ticks ('✓') in each row. |Pseudocode example|Selection|Iteration|Subroutine| |---|---|---|---| |FOR Index~~←~~ 1 TO 3<br> IF Safe[Index] = TRUE THEN<br> Flap[Index]← 0<br> ENDIF<br>NEXT Index|||| |CASE OF Compound(3)|||| |REPEAT UNTIL AllDone() = TRUE|||| |WHILE Result[3] <> FALSE|||| ### (b) Complete the table by giving the appropriate data type in each case. <span class="part-marks">3 marks</span> |Variable|Example data value|Data type| |---|---|---| |Available|TRUE|| |Received|"18/04/2021"|| |Index|100|| ### (c) Evaluate each expression in the table by using the data values shown in part (b). <span class="part-marks">3 marks</span> Write ‘ERROR’ if the expression contains an error. |Expression|Evaluates to| |---|---| |Available AND NOT(Index > 100)|| |Index MOD 30|| |NUM_TO_STR(Index + "33")||
Show mark scheme

1(a) [4 marks]

Pseudocode example Selection Iteration Subroutine  FOR Index 1 TO 3 IF Safe[Index] = TRUE THEN    Flap[Index] 0 ENDIF NEXT Index CASE OF Compound(3)   REPEAT UNTIL AllDone() = TRUE   WHILE Result[3] <> FALSE  One mark per row

1(b) [3 marks]

Variable Example data value Data type Available TRUE BOOLEAN Received "18/04/2021" STRING Index 100 INTEGER One mark per row

1(c) [3 marks]

Expression Evaluates to Available AND NOT(Index > 100) TRUE Index MOD 30 10 NUM_TO_STR(Index + "33") ERROR One mark per row DECLARE Count, Total, NextNumber : INTEGER

Q1
May/Jun 2024 Paper 2 v1

An algorithm is developed in pseudocode before being coded in a programming language.

(a) The following table shows four valid pseudocode assignment statements. 4 marks

Complete the table by giving an a and D. appropriate data type to declare e
Assignment statement Data type
A
LEFT(MyName, 1)
B
Total * 2
C
INT(ItemCost) / 3
D
"Odd OR Even"

(b) Other variables in the program have example values as shown: 4 marks

Variable Value
Sorted False
Tries 9
ID "ZGAC001"

Complete the table by evaluating each expression, using the example values.

Expression Evaluates to
Tries < 10 AND NOT Sorted
Tries MOD 4
TO_LOWER(MID(ID, 3, 1))
LENGTH(ID & "xx") >= Tries
An algorithm is developed in pseudocode before being coded in a programming language. ### (a) The following table shows four valid pseudocode assignment statements. <span class="part-marks">4 marks</span> |Complete the table by giving an a and D.|appropriate data type to declare e| |---|---| |**Assignment statement**|**Data type**| |`A `<br>` LEFT(MyName, 1)`|| |`B `<br>` Total * 2`|| |`C `<br>` INT(ItemCost) / 3`|| |`D `<br>` "Odd OR Even"`|| ### (b) Other variables in the program have example values as shown: <span class="part-marks">4 marks</span> |Variable|Value| |---|---| |`Sorted`|`False`| |`Tries`|`9`| |`ID`|`"ZGAC001"`| Complete the table by evaluating each expression, using the example values. |Expression|Evaluates to| |---|---| |`Tries < 10 AND NOT Sorted`|| |`Tries MOD 4`|| |`TO_LOWER(MID(ID, 3, 1))`|| |`LENGTH(ID & "xx") >= Tries`||
Show mark scheme

1(a) [4 marks]

Assignment statement Data type  CHAR / STRING A LEFT(MyName, 1)  INTEGER / REAL B Total * 2  REAL C INT(ItemCost) / 3  STRING D "Odd OR Even" One mark per row

1(b)

Expression Evaluates to Tries < 10 AND NOT Sorted TRUE Tries MOD 4 1 TO_LOWER(MID(ID, 3, 1)) 'a' // "a" LENGTH(ID & "xx") >= Tries TRUE One mark per row

1(c)(i) [1 mark]

The names do not reflect / indicate the purpose of the variable // the names are not meaningful

1(c)(ii) [1 mark]

They make the program more difficult to understand / debug / maintain

1(c)(iii)

One mark from:  Indentation / use of white space  Capitalisation of keywords  Use of comments  Use of modular programming  Use of local variables Note: max 1 mark

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

Q1
May/Jun 2024 Paper 2 v2

(a) The following table contains pseudocode examples. 4 marks

Each example may contain statements that relate to one or more of the following:

  • selection

  • iteration (repetition)

  • input/output.

Complete the table by placing one or more ticks (3) in each row.

Pseudocode example Selection Iteration Input/Output
FOR Index
1 TO 10
Data[Index]
0
NEXT Index

WRITEFILE ThisFile, "****"
UNTIL Level > 25
IF Mark > 74 THEN
READFILE OldFile, Data
ENDIF

(b) Program variables have data types as follows: 4 marks

Variable Data type
MyChar CHAR
MyString STRING
MyInt INTEGER

Complete the table by filling in each gap with a function (from the insert ) so that each expression is valid.

### (a) The following table contains pseudocode examples. <span class="part-marks">4 marks</span> Each example may contain statements that relate to one or more of the following: - selection - iteration (repetition) - input/output. Complete the table by placing **one or more** ticks (3) in each row. |Pseudocode example|Selection|Iteration|Input/Output| |---|---|---|---| |`FOR Index`<br>` 1 TO 10`<br>` Data[Index]`<br>` 0`<br>`NEXT Index`|||| |<br>`WRITEFILE ThisFile, "****"`|||| |`UNTIL Level > 25`|||| |`IF Mark > 74 THEN`<br>` READFILE OldFile, Data`<br>`ENDIF`|||| ### (b) Program variables have data types as follows: <span class="part-marks">4 marks</span> |Variable|Data type| |---|---| |`MyChar`|`CHAR`| |`MyString`|`STRING`| |`MyInt`|`INTEGER`| Complete the table by filling in each gap with a function (from the **insert** ) so that each expression is valid. ![](../images/s24_22_q1_fig1.png)
Show mark scheme

1(a) [4 marks]

Pseudocode example Selection Iteration Input/Output  FOR Index 1 TO 10   Data[Index] 0 NEXT Index WRITEFILE ThisFile,  "****" UNTIL Level > 25  IF Mark > 74 THEN READFILE OldFile,   Data ENDIF One mark per row.

1(b)

Expression  INT MyInt (3.1415926)  MID MyChar ("Elwood", 3, 1) Any of:   MyString NUM_TO_STR ( INT (27.509))   MyString CHR ( INT (27.509))   MyString TO_UPPER ( NUM_TO_STR( 27.509))   MyString TO_LOWER ( NUM_TO_STR ( 27.509)) Any of:   STR_TO_NUM ( RIGHT MyInt ("ABC123", 3))   LENGTH ( RIGHT MyInt ("ABC123", 3))   LENGTH ( LEFT MyInt ("ABC123", 3)) One mark per row

1(c) [5 marks]

1 mark for stating a suitable way of documenting:  Identifier table 1 mark for giving one piece of information that should be recorded. examples include: Explanation of what (each) variable is used for The purpose of (each) variable An example of data values stored // Initialisation value

Q4
May/Jun 2024 Paper 2 v2

A triangle has sides of length A, B and C.

In this example, A is the length of the longest side.

This triangle is said to be right‑angled if the following equation is true:

A × A = (B × B) + (C × C)

A procedure will be written to check whether three lengths represent a right‑angled triangle. The lengths will be input in any sequence.

The procedure IsRA() will:

  • prompt and input three integer values representing the three lengths

  • test whether the three lengths correspond to the sides of a right‑angled triangle

  • output a suitable message.

The length of the longest side may not be the first value input.

Write pseudocode for the procedure IsRA() . 5 marks

A triangle has sides of length A, B and C. In this example, A is the length of the longest side. This triangle is said to be right‑angled if the following equation is true: A × A = (B × B) + (C × C) A procedure will be written to check whether three lengths represent a right‑angled triangle. The lengths will be input in any sequence. The procedure `IsRA()` will: - prompt and input three integer values representing the three lengths - test whether the three lengths correspond to the sides of a right‑angled triangle - output a suitable message. The length of the longest side may **not** be the first value input. Write pseudocode for the procedure `IsRA()` . <span class="part-marks">5 marks</span>
Show mark scheme

4 Example solution:

PROCEDURE IsRA() DECLARE a, b, c : INTEGER OUTPUT "Input length of the first side" INPUT a OUTPUT "Input length of the second side" INPUT b OUTPUT "Input length of the third side" INPUT c IF (a * a = (b * b) + (c * c)) OR__ (b * b = (a * a) + (c * c)) OR__ (c * c = (a * a) + (b * b)) THEN OUTPUT "It is right-angled" ELSE OUTPUT "Not right-angled" ENDIF ENDPROCEDURE Mark as follows:

  1. Procedure heading and ending and declaration of all variables used
  2. Appropriate prompt and input for each length

One correct length test 4. All three length tests // selection of which test is required 5. Output one of two messages following a reasonable attempt at MP3

Q5
May/Jun 2024 Paper 2 v2

A program is being designed in pseudocode.

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

The first element has the index value 1.

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

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

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

Identify the errors.

Syntax error 1

Syntax error 2

Other error

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

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

Statement

Explanation

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

When the program is executed it unexpectedly stops responding.

Identify the type of error that has occurred.

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

5(a)(i) [2 marks]

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

5(a)(ii)

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

5(b) [7 marks]

Run-time

Q6
May/Jun 2024 Paper 2 v2

A music player stores music in a digital form and has a display which shows the track being played.

(a) Up to 16 characters can be displayed. Track titles longer than 16 characters will need to be trimmed as follows: 7 marks

  • Words must be removed from the end of the track title until the resulting title is less than 14 characters.

  • When a word is removed, the space in front of that word is also removed.

  • Three dots are added to the end of the last word displayed when one or more words have been removed.

The table below shows some examples:

Original title Display string

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
B a t o u t o f H u l l
B o h e m i a n . . .
P a p e r b o o k W r i t e r
C h r i s S i n g s . . .
G r e e n H o m e . . .

A function Trim() will:

  • take a string representing the original title

  • return the string to be displayed.

Assume:

  • Words in the original title are separated by a single space character.

  • There are no spaces before the first word or after the last word of the original title.

  • The first word of the original title is less than 14 characters.

Write pseudocode for the function Trim() .

(b) Music is stored as a sequence of digital samples.

Each digital sample is a denary value in the range 0 to 99999999 (8 digits).

The samples are to be stored in a text file. Each sample is converted to a numeric string and 32 samples are concatenated (joined) to form a single line of the text file.

Each numeric string is 8 characters in length; leading ‘0’ characters are added as required.

Example:
Sample Denary value String
1 456 "00000456"
2 48 "00000048"
3 37652 "00037652"
32 673 "00000673"

The example samples will be stored in the text file as a single line:

    "000004560000004800037652...00000673"

(i) Identify one drawback of adding leading ‘0’ characters to each numeric string. 1 mark

(ii) Suggest an alternative method of storing the samples which does not involve adding leading ‘0’ characters but which would still allow each individual sample to be extracted. 1 mark

(iii) State one drawback of the alternative method given in part (b)(ii) . 1 mark

A music player stores music in a digital form and has a display which shows the track being played. ### (a) Up to 16 characters can be displayed. Track titles longer than 16 characters will need to be trimmed as follows: <span class="part-marks">7 marks</span> - Words must be removed from the end of the track title until the resulting title is less than 14 characters. - When a word is removed, the space in front of that word is also removed. - Three dots are added to the end of the last word displayed when one or more words have been removed. The table below shows some examples: **Original title** **Display string** |1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16| |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| |**B**|**a**|**t**||**o**|**u**|**t**||**o**|**f**||**H**|**u**|**l**|**l**|| |**B**|**o**|**h**|**e**|**m**|**i**|**a**|**n**|**.**|**.**|**.**|||||| |**P**|**a**|**p**|**e**|**r**|**b**|**o**|**o**|**k**||**W**|**r**|**i**|**t**|**e**|**r**| |**C**|**h**|**r**|**i**|**s**||**S**|**i**|**n**|**g**|**s**|**.**|**.**|**.**||| |**G**|**r**|**e**|**e**|**n**||**H**|**o**|**m**|**e**|**.**|**.**|**.**|||| A function `Trim()` will: - take a string representing the original title - return the string to be displayed. Assume: - Words in the original title are separated by a single space character. - There are no spaces before the first word or after the last word of the original title. - The first word of the original title is less than 14 characters. Write pseudocode for the function `Trim()` . ### (b) Music is stored as a sequence of digital samples. Each digital sample is a denary value in the range 0 to 99999999 (8 digits). The samples are to be stored in a text file. Each sample is converted to a numeric string and 32 samples are concatenated (joined) to form a single line of the text file. Each numeric string is 8 characters in length; leading ‘0’ characters are added as required. |Example:||| |---|---|---| |**Sample**|**Denary value**|**String**| |1|`456`|`"00000456"`| |2|`48`|`"00000048"`| |3|`37652`|`"00037652"`| |||| |32|`673`|`"00000673"`| The example samples will be stored in the text file as a single line: ``` "000004560000004800037652...00000673" ``` #### (i) Identify one drawback of adding leading ‘0’ characters to each numeric string. <span class="part-marks">1 mark</span> #### (ii) Suggest an alternative method of storing the samples which does **not** involve adding leading ‘0’ characters but which would still allow each individual sample to be extracted. <span class="part-marks">1 mark</span> #### (iii) State **one** drawback of the alternative method given in part **(b)(ii)** . <span class="part-marks">1 mark</span>
Show mark scheme

6(a)

Example solution: Function Trim(Name : STRING) RETURNS STRING CONSTANT Dots = "..." CONSTANT Space = " " IF LENGTH(Name) <= 16 THEN RETURN Name ENDIF // Otherwise it has to be trimmed WHILE LENGTH(Name) > 13 REPEAT  Name LEFT(Name, LENGTH(Name) - 1) // strip last char UNTIL RIGHT(Name, 1) = Space // back to SPACE ENDWHILE  Name LEFT(Name, LENGTH(Name) - 1) // remove the space  Name Name & Dots RETURN Name ENDFUNCTION Mark as follows:

  1. Function heading, ending, parameter and return type
  2. If length of original string <= 16 then return original string
  3. Any Conditional loop...
  4. until string is short enough
  5. Inner conditional loop / second condition to identify word(s) to remove from the end of string // Check to identify word(s) to remove from the end of string
  6. Attempt to strip characters back to space
  7. Correct removal of word/words from end of string and remove final space
  8. Concatenate and return result Dots Max 7 marks

6(b)(i) [1 mark]

A (very) large file is created // redundant zeroes are stored in the file

6(b)(ii) [1 mark]

One mark for:  Values are delimited by a special character / a separator character  First character indicates sample length Max 1 mark

6(b)(iii) [3 marks]

The algorithm to store / extract / separate the individual values is more complex / takes longer to execute / run / process NE Algorithm is more complicated

Q6
May/Jun 2024 Paper 2 v3

A program displays a progress bar to inform the user of the progress of tasks that take a significant time to complete, such as those involving file transfer operations.

Task progress is divided into 11 steps. Each step represents the amount of progress as a percentage. An image is associated with each step and each image is stored in a different file.

Different progress bar images may be selected. For a given image, files all have the same filename root, with a different suffix.

The table illustrates the process for using the image with filename root BargraphA

Step Percentage
progress
Image filename Image
1 < 10 BargraphA-1.bmp
2 >= 10 and < 20 BargraphA-2.bmp
3 >= 20 and < 30 BargraphA-3.bmp
9 >= 80 and < 90 BargraphA-9.bmp
10 >= 90 and < 100 BargraphA-10.bmp
11 100 BargraphA-11.bmp

A procedure Progress() will:

  • be called with two parameters:

  • an integer representing the percentage progress (0 to 100 inclusive)

  • a string representing the image filename root

  • generate the full image filename

  • call a procedure Display() using the full image filename as the parameter.

(a) Write pseudocode for procedure Progress(). 6 marks

(b) The definition of procedure Progress() is provided here for reference:

A procedure Progress() will:

  • be called with two parameters:

  • an integer representing the percentage progress (0 to 100 inclusive)

  • a string representing the image filename root

  • generate the full image filename

  • call a procedure Display() using the full image filename as the parameter.

Progress() will be rewritten and a new module Progress2() produced with these requirements:

  • an additional parameter of type integer will specify the total number of steps

  • the image filename will be returned (procedure Display() will not be called from within Progress2()).

(i) Write pseudocode for the new module header. 2 marks

(ii) State one benefit of increasing the number of steps. 1 mark

A program displays a progress bar to inform the user of the progress of tasks that take a significant time to complete, such as those involving file transfer operations. Task progress is divided into 11 steps. Each step represents the amount of progress as a percentage. An image is associated with each step and each image is stored in a different file. Different progress bar images may be selected. For a given image, files all have the same filename root, with a different suffix. The table illustrates the process for using the image with filename root BargraphA |Step|Percentage<br>progress|Image filename|Image| |---|---|---|---| |1|< 10|BargraphA-1.bmp|| |2|>= 10 and < 20|BargraphA-2.bmp|| |3|>= 20 and < 30|BargraphA-3.bmp|| ||||| |9|>= 80 and < 90|BargraphA-9.bmp|| |10|>= 90 and < 100|BargraphA-10.bmp|| |11|100|BargraphA-11.bmp|| A procedure Progress() will: - be called with two parameters: - an integer representing the percentage progress (0 to 100 inclusive) - a string representing the image filename root - generate the full image filename - call a procedure Display() using the full image filename as the parameter. ### (a) Write pseudocode for procedure Progress(). <span class="part-marks">6 marks</span> ### (b) The definition of procedure Progress() is provided here for reference: A procedure Progress() will: - be called with two parameters: - an integer representing the percentage progress (0 to 100 inclusive) - a string representing the image filename root - generate the full image filename - call a procedure Display() using the full image filename as the parameter. Progress() will be rewritten and a new module Progress2() produced with these requirements: - an additional parameter of type integer will specify the total number of steps - the image filename will be returned (procedure Display() will **not** be called from within Progress2()). #### (i) Write pseudocode for the new module header. <span class="part-marks">2 marks</span> #### (ii) State **one** benefit of increasing the number of steps. <span class="part-marks">1 mark</span>
Show mark scheme

6(a)

Example Selection Solution: PROCEDURE Progress(Percent : INTEGER, Root : STRING) DECLARE Filename, StepValue : STRING CASE OF Percent  < 10 : StepValue "1"  < 20 : StepValue "2"  < 30 : StepValue "3"  < 40 : StepValue "4"  < 50 : StepValue "5"  < 60 : StepValue "6"  < 70 : StepValue "7"  < 80 : StepValue "8"  < 90 : StepValue "9"  < 100 : StepValue "10"  OTHERWISE : StepValue "11" ENDCASE  Filename Root & "-" & StepValue & ".bmp" CALL Display(Filename) ENDPROCEDURE Mark as follows for loop solution: 1 Procedure heading, parameters and ending 2 Correct selection construct(s) structure 3 Use of selection statement to obtain two file numbers 4 Use of selection statement to obtain all the file numbers 5 Concatenate , hyphen, file number and ".bmp" suffix Root 6 Call once with filename as parameter following a reasonable Display() attempt

6(b)(i) [2 marks]

Example answer: FUNCTION Progress2(Percent, Steps : INTEGER, Root : STRING) RETURNS STRING One mark for each:  Keyword and three parameters of correct type FUNCTION Progress2  Keyword and type string RETURNS

6(b)(ii) [1 mark]

The progress display will more accurately show the progress of the task

Q1
Oct/Nov 2023 Paper 2 v1

3 marks

<span class="part-marks">3 marks</span>
Show mark scheme

1(a) [4 marks]

One mark per row: The value assigned to when is 40 "Medium" Level ThisValue The value assigned to Check when is 36 12 ThisValue The value assigned to Level when is 18 "Low" ThisValue The number of elements in array Data that may be 11 incremented

1(b) [3 marks]

One mark for identifying assignment:  MP1 // the level is assigned value “very low” Level "Very Low" Explanation points: MP2 because CASE clauses are checked in sequence // because of the order of the clauses MP3 a value < 30 satisfies the first clause // Clause '< 20' will never be tested

1(c) [1 mark]

MP1 all of the possible values are addressed via all / four / three / the other clauses // there are no other possible values to map to OTHERWISE

1(d) [3 marks]

One mark per point: • : INTEGER ThisValue • : REAL Check • : STRING Level

Q3
Oct/Nov 2023 Paper 2 v1

BottomOfStack

`BottomOfStack`
Show mark scheme

3(a) [3 marks]

MP1 all values in the order and location shown MP2 value is index of element containing D1 TopOfStack MP3 value is index of element containing D2 BottomOfStack MP1 If = 8 // (stack) full then return

3(b) [5 marks]

TopOfStack FALSE MP2 Otherwise, increment TopOfStack MP3 Use as an index to the Array TopOfStack MP4 Set the element at this index / location / position to the value / data / item being added MP5 Return TRUE FUNCTION TooMany(Search : STRING, Max : INTEGER) RETURNS

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

Q1
Oct/Nov 2023 Paper 2 v2

D32 2

2 3

D32 2 **2** 3
Show mark scheme

1(a) [4 marks]

One mark for each row with appropriate variable name and data type Example Explanation Variable name Data value type "Mr Khan" CustomerName STRING The name of the customer 3 NumItems INTEGER The number of items in the order TRUE NewCustomer BOOLEAN A value to indicate whether this is a new customer 15.75 Deposit REAL The deposit paid by the customer

1(b) [4 marks]

One mark per row Expression Evaluates to (Total * DepRate) + 1.5 249.50 RIGHT(Description, 7) "(small)" (LENGTH(Description) - 8) > 16 TRUE NUM_TO_STR(INT(DepRate * 10)) & '%' "20%"

1(c) [3 marks]

One mark per point Max 3 marks Declaration 1 Declare a composite / record (type) 2 Declare an array of the given composite / record (type) Expansion of record: 3 … containing all data items required // containing items of different data types Expansion of array: 4 … where each array element represents data for one order / customer (order)

Q3
Oct/Nov 2023 Paper 2 v2
Show mark scheme

3(a) [5 marks]

Mark as follows: • One mark for value Start_Pointer • One mark each group of row(s): • 2 • 3 and 4 • 5 • 7 and 8 For null pointer: accept 0 / / an out-of-bound index value less than 1, greater ∅ than 8

3(b) [4 marks]

One mark per step: 1 Assign the data item D6 to F1 2 Set the pointer of this node to point to D11 3 Set Ptr2 to point to F2 4 Set pointer of D32 to point to D6

Q1
Oct/Nov 2023 Paper 2 v3
Show mark scheme

1(a) [4 marks]

Assignment statement Data type  REAL MyVar1 Total1 / Total2  DATE MyVar2 27/10/2023  STRING MyVar3 "Sum1 / Sum2"  BOOLEAN MyVar4 Result1 AND Result2

1(b) [4 marks]

Expression Evaluates to Fraction >= 0.2 AND NOT Active FALSE INT((Fraction1 * 100) + 13.3) 33 STR_TO_NUM(MID(Code, 4, 2)) + 5 28 LENGTH("TRUE" & Code) 11

1(c) [1 mark]

The use of a program library (routines)

1(d) [2 marks]

MP1 Type: Adaptive MP2 Reason: The (user) requirement(s) changes // to accommodate legislative changes

Q3
Oct/Nov 2023 Paper 2 v3

4 Variable

**4** **Variable**
Show mark scheme

3(a) [3 marks]

: MP1 D3, D4, D1, D2 and D5 in question order or reversed - in any five consecutive locations MP2 value matches index with D3 FoQ MP3 value matches index with D5 EoQ MP1 If is / = 8 // (queue) full then jump to step 6

3(b) [6 marks]

NumItems MP2 Increment EndOfQueue MP3 If = 9 then set to 1 EndOfQueue EndOfQueue MP4 Increment NumItems MP5 Set the Element at the index … MP6 stored in to value/data/item being added EndOfQueue Mark as follows: Steps 1 to 4: One mark for gaps filled as shown Step 5: One mark for 'element' and one mark for other two terms PROCEDURE RandList()

Q6
Oct/Nov 2023 Paper 2 v3

A function TestNum() will take a six-digit string as a parameter.

The function will as follows: l test whether the string meets certain conditions and will retu urn an integer va
Return value Condition Example
1 The last three digits are the same but non-zero. "253444"
2 The last three digits are zero. "253000"
3 The first three and last three digits are the same. "410410"

The function will return the highest possible value for the given string.

If the string does not meet any of the conditions, zero is returned.

Write pseudocode for function TestNum() .

Assume that the parameter is valid. 6 marks

A function `TestNum()` will take a six-digit string as a parameter. |The function will as follows:|l test whether the string meets certain conditions and will retu|urn an integer va| |---|---|---| |**Return value**|**Condition**|**Example**| |1|The last three digits are the same but non-zero.|"253444"| |2|The last three digits are zero.|"253000"| |3|The first three and last three digits are the same.|"410410"| The function will return the highest possible value for the given string. If the string does not meet any of the conditions, zero is returned. Write pseudocode for function `TestNum()` . Assume that the parameter is valid. <span class="part-marks">6 marks</span>
Show mark scheme

6 [6 marks]

FUNCTION TestNum(ThisNum : STRING) RETURNS INTEGER IF LEFT(ThisNum,3) = RIGHT(ThisNum 3) THEN RETURN 3 ENDIF IF RIGHT(ThisNum, 3) = "000" THEN RETURN 2 ENDIF IF MID(ThisNum, 4, 1) = MID(ThisNum, 5, 1)__ AND MID(ThisNum, 5, 1) = MID(ThisNum, 6, 1) THEN RETURN 1 ENDIF RETURN 0 ENDFUNCTION MP1 Function heading and ending including parameter and return type MP2 Test for Condition 1 MP3 Test for Condition 2 MP4 Test for Condition 3 MP5 Return the highest value if more than one condition is satisfied MP6 Return zero if no condition matched

Q1
May/Jun 2023 Paper 2 v1
Show mark scheme

1(a) [3 marks]

For example: Could set a breakpoint to stop the program at a particular point / instruction then the value of variables could be checked using a report/watch window while single stepping can be used to execute one statement/line at a time. Marks available as follows:  One mark for each underlined term  One mark for an explanation of each term Note: max 4 marks

1(b) [2 marks]

One mark for correct description of: Error 1: Brackets mismatch // 2/value should be added after brackets/function // Addition between a string and a number is not valid // STR_TO_NUM / the function needs to be passed a string / not an integer Error 2: No Error Error 3: returns an integer and this is being compared with a MONTH() character/string // Integer cannot be compared to a string // 6 should not be in quotes

1(c)(i)

Expression Evaluation (Points > 99) OR Active 1 TRUE (Points MOD 2 = 0) OR Exempt 2 FALSE (Points <= 75) AND (Active OR Exempt) 3 TRUE (Active OR NOT Active) AND NOT Exempt 4 TRUE One mark for any two rows correct Two marks for all rows correct NOT Exempt

Q4
May/Jun 2023 Paper 2 v1

Function Replace() will:

  1. take three parameters:
  • a string (the original string)

  • a char (the original character)

  • a char (the new character)

  1. form a new string from the original string where all instances of the original character are replaced by the new character

  2. return the new string.

Write pseudocode for function Replace() . 6 marks

Function `Replace()` will: 1. take three parameters: - a string (the original string) - a char (the original character) - a char (the new character) 2. form a new string from the original string where all instances of the original character are replaced by the new character 3. return the new string. Write pseudocode for function `Replace()` . <span class="part-marks">6 marks</span>
Show mark scheme

4 [2 marks]

CHAR) __ RETURNS : STRING DECLARE NewString : STRING DECLARE ThisChar : CHAR DECLARE Index : INTEGER  NewString ""  FOR Index 1 TO LENGTH(OldString)  ThisChar MID(OldString, Index, 1) IF ThisChar = Char1 THEN  ThisChar Char2 ENDIF  NewString NewString & ThisChar NEXT Index RETURN NewString ENDFUNCTION Mark as follows: 1 Function heading and ending, including parameters and return type 2 Declaration of local variables used including loop counter 3 Loop for length of OldString 4 Extract char and test in a loop 5 Use of concatenate to build replace char if necessary, NewString in a loop 6 Return after reasonable attempt NewString

Q1
May/Jun 2023 Paper 2 v2
Show mark scheme

1(a)(i) [3 marks]

Use of constants

1(a)(ii)

One mark per bullet point (or equivalent to max 3): 1 Postal rates are entered once only 2 Avoids input error / changing the cost accidentally // avoids different values for postal rates at different points in the program 3 When required, the constant representing the postal rate value is changed once only // easier to maintain the program when the postal rates change 4 Makes the program easier to understand Note: Max 3 marks

1(b) [3 marks]

One mark per bullet point:  Indentation  White space  Comments  Sensible / meaningful variable names // use of Camel Case  Capitalised keywords Note: Max 3 marks

1(c) [3 marks]

One mark per bullet point:  BOOLEAN  REAL  STRING 

Q4
May/Jun 2023 Paper 2 v2

A function GetNum() will:

  1. take two parameters: a string and a character
  2. count the number of times that the character occurs in the string
  3. return the count.

Any comparison between characters needs to be case sensitive. For example, character ' a ' and character ' A ' are not identical.

Write pseudocode for function GetNum() . 6 marks

A function `GetNum()` will: 1. take two parameters: a string and a character 2. count the number of times that the character occurs in the string 3. return the count. Any comparison between characters needs to be case sensitive. For example, character ' `a` ' and character ' `A` ' are not identical. Write pseudocode for function `GetNum()` . <span class="part-marks">6 marks</span>
Show mark scheme

4 [3 marks]

RETURNS INTEGER DECLARE Index, Count : INTEGER  Count 0  FOR Index 1 TO LENGTH(ThisString) IF MID(ThisString, Index, 1) = ThisChar THEN  Count Count + 1 ENDIF NEXT Index RETURN Count ENDFUNCTION Mark as follows: 1 Function heading and end, including parameters and return type 2 Declare local Integers for and Index Count 3 Loop for length of ThisString 4 Extract a character and compare with parameter in a loop 5 Increment if match in a loop Count 6 Return after loop Count

Q4
May/Jun 2023 Paper 2 v3

A function MakeString() will: 1 . take two parameters:

  • a count as an integer

  • a character 2 . generate a string of length equal to the count, made up of the character 3 . return the string generated, or return "ERROR" if the count is less than 1.

For example, the function call:

MakeString(3, 'Z') will return the string "ZZZ"

Write pseudocode for function MakeString() . 6 marks

A function `MakeString()` will: 1 **.** take two parameters: - a count as an integer - a character 2 **.** generate a string of length equal to the count, made up of the character 3 **.** return the string generated, or return `"ERROR"` if the count is less than 1. For example, the function call: `MakeString(3, 'Z')` will return the string `"ZZZ"` Write pseudocode for function `MakeString()` . <span class="part-marks">6 marks</span>
Show mark scheme

4 [3 marks]

RETURNS STRING DECLARE MyString : STRING DECLARE Index : INTEGER IF Count < 1 THEN  MyString "ERROR" ELSE  MyString ""  FOR Index 1 TO Count  MyString MyString & AChar NEXT Index ENDIF RETURN MyString ENDFUNCTION MP1 Function heading and end including parameters and return type MP2 Declaration of locals and Index MyString MP3 Test for < 1 and if true, assign "ERROR" to / Count MyString Immediate RETURN MP4 Loop for iterations Count MP5 Use of concatenate – must have been initialised in a loop MP6 Return STRING (correctly in both cases)

Q1
Oct/Nov 2022 Paper 2 v1

(a) An algorithm includes a number of complex calculations. A programmer is writing a program to implement the algorithm and decides to use library routines to provide part of the solution. 3 marks

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

1

2

3

(b) The following pseudocode is part of a program that stores names and test marks for use in other parts of the program.

    DECLARE Name1, Name2, Name3 : STRING
    DECLARE Mark1, Mark2, Mark3 : INTEGER
    INPUT Name1
    INPUT Mark1
    INPUT Name2
    INPUT Mark2
    INPUT Name3
    INPUT Mark3

(i) The pseudocode needs to be changed to allow for data to be stored for up to 30 students. 3 marks

Explain why it would be good practice to use arrays to store the data.

### (a) An algorithm includes a number of complex calculations. A programmer is writing a program to implement the algorithm and decides to use library routines to provide part of the solution. <span class="part-marks">3 marks</span> State **three** possible benefits of using library routines in the development of the program. 1 2 3 ### (b) The following pseudocode is part of a program that stores names and test marks for use in other parts of the program. ``` DECLARE Name1, Name2, Name3 : STRING DECLARE Mark1, Mark2, Mark3 : INTEGER INPUT Name1 INPUT Mark1 INPUT Name2 INPUT Mark2 INPUT Name3 INPUT Mark3 ``` #### (i) The pseudocode needs to be changed to allow for data to be stored for up to 30 students. <span class="part-marks">3 marks</span> Explain why it would be good practice to use arrays to store the data.
Show mark scheme

1(a) [3 marks]

One mark per point: 1 They are tried and tested so free from errors 2 They perform a function that you may not be able to program yourself (for example encryption ) 3 They are readily available / speed up development time

1(b)(i) [3 marks]

One mark per point: 1 Algorithm to process / search / organise the data is easier to implement // Values may be accessed via a loop-controlled variable / iterated through using index 2 Makes the program easier to design / code / test / understand 3 Multiple instances referenced via a single identifier / so fewer identifiers needed // Easier to amend the program when the number of students increases

1(b)(ii) [2 marks]

One mark per point: Purpose : It identifies / references an individual array element // provides the index to the array Data type : Integer

1(c) [4 marks]

One mark per row: Statement Error   Should be "=" not IF EMPTY "" THEN  Parameter should be a string (or Status IS_NUM(-23.4) char) // should not be a real  NO ERROR X STR_TO_NUM("37") + 5  Wrong operator – should be & or Y STR_TO_NUM("37" + "5") Parameter is not a string

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

Q1
Oct/Nov 2022 Paper 2 v2

(a) A programmer is developing an algorithm to solve a problem. Part of the algorithm would be appropriate to implement as a subroutine (a procedure or a function).

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

1

2

(ii) A procedure header is shown in pseudocode: 2 marks

     PROCEDURE MyProc(Count : INTEGER, Message : STRING)

Give the correct term for the identifiers Count and Message and explain their use.

Term

Use

(b) The algorithm in part (a) is part of a program that will be sold to the public. 4 marks

All the software errors that were identified during in-house testing have been corrected.

Identify and describe the additional test stage that may be carried out before the program is sold to the public.

Test stage

Description

### (a) A programmer is developing an algorithm to solve a problem. Part of the algorithm would be appropriate to implement as a subroutine (a procedure or a function). #### (i) State **two** reasons why the programmer may decide to use a subroutine. <span class="part-marks">2 marks</span> 1 2 #### (ii) A procedure header is shown in pseudocode: <span class="part-marks">2 marks</span> ``` PROCEDURE MyProc(Count : INTEGER, Message : STRING) ``` Give the correct term for the identifiers `Count` and `Message` **and** explain their use. Term Use ### (b) The algorithm in **part (a)** is part of a program that will be sold to the public. <span class="part-marks">4 marks</span> All the software errors that were identified during in-house testing have been corrected. Identify **and** describe the additional test stage that may be carried out before the program is sold to the public. Test stage Description
Show mark scheme

1(a)(i) [2 marks]

One mark for each point ( Max 2 ): • When a task which is repeated / reused / performed in several places • When a part of an algorithm performs a specific task • Reduces complexity of program / program is simplified // subroutine already available • Testing / debugging / maintenance is easier

1(a)(ii) [2 marks]

One mark for each part: Term : Parameter(s) Use : to pass values / arguments to the procedure

1(b) [4 marks]

One mark for test stage, one mark for each description point (Max 3 for Description) Test stage : Beta testing Description : 1 Testing carried out by a small group of (potential) users 2 Users will check that the software works as required / works in the real world / does not contain errors 3 Users will feedback problems / suggestions for improvement 4 Problems / suggestions identified are addressed (before the program is sold)

1(c) [3 marks]

One mark per row: Expression Evaluation MID(CharList, MONTH(FlagDay), 1) 'D' INT(Count / LENGTH(CharList)) 4 (Count >= 99) AND (DAY(FlagDay) > 23) 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

Q1
Oct/Nov 2022 Paper 2 v3

A program is required for a shopping website.

(a) Part of the program requires four variables. The following table describes the use of each variable. 4 marks

Complete the table by adding the most appropriate data type for each variable.

Variable use Data type
Store the number of days in the current month
Store the first letter of the customer’s first name
Store an indication of whether a year is a leap year
Store the average amount spent per customer visit

(b) The designer considers the use of a development life cycle to split the development of the website into several stages.

(i) State one benefit of a development life cycle when developing the website. 1 mark

(ii) Analysis is one stage of a development life cycle. 1 mark

State one document that may be produced from the analysis stage of the website project.

A program is required for a shopping website. ### (a) Part of the program requires four variables. The following table describes the use of each variable. <span class="part-marks">4 marks</span> Complete the table by adding the most appropriate data type for each variable. |Variable use|Data type| |---|---| |Store the number of days in the current month|| |Store the first letter of the customer’s first name|| |Store an indication of whether a year is a leap year|| |Store the average amount spent per customer visit|| ### (b) The designer considers the use of a development life cycle to split the development of the website into several stages. #### (i) State **one** benefit of a development life cycle when developing the website. <span class="part-marks">1 mark</span> #### (ii) Analysis is one stage of a development life cycle. <span class="part-marks">1 mark</span> State **one** document that may be produced from the analysis stage of the website project.
Show mark scheme

1(a) [4 marks]

One mark per row Variable use Data type Store the number of days in the current month INTEGER Store the first letter of the customer's first name CHAR Store an indication of whether a year is a leap BOOLEAN year Store the average amount spent per customer REAL visit

1(b)(i) [1 mark]

Easier to manage/plan/cost // Clear deliverables produced at (end of) each stage

1(b)(ii) [1 mark]

One mark per point ( Max 1 ): • The problem definition • Requirements specification // Client requirements • Documentation related to current system (e.g. ER diagram of current system, DFD of current system, feasibility study)

1(c)(i) [1 mark]

One mark per point ( Max 1 ): • Modules are developed in parallel / as prototypes • Minimal / no detailed planning is carried out // Allows for changes to requirements • Flexible development process • Small incremental releases are made, each adding functionality • Used for time critical development • Client involved during (all stages) of development

1(c)(ii) [3 marks]

Examples include: Benefits: (Max 2 marks) • Quicker development possible / Multiple areas can be worked on at same time • Prototype produced (at early stage in process) • Easier to change requirements / quicker delivery of usable modules • Early review possible / closer cooperation between client and developers Drawback: (Max 1 mark) • Difficult to estimate cost / time to complete project • Documentation often omitted • Lack of client availability throughout life cycle // too easy for client to keep changing their mind

1(d) [2 marks]

One mark for each point ( Max 2 ) Examples include: 1 Change to website requirements 2 New technologies available to host website // changes made to library modules used 3 Change in relevant legislation

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

Q6
May/Jun 2022 Paper 2 v1

(a) An algorithm will: 5 marks

  • output each integer value between 100 and 200 that ends with the digit 7, for example, 107

  • output a final count of the number of values that are output.

Write pseudocode for this algorithm.

Any variables used must be declared.

(b) Study the following pseudocode. 4 marks

    CASE OF MySwitch
    1: ThisChar  'a'
    2: ThisChar  'y'
    3: ThisChar  '7'
    OTHERWISE: ThisChar  '*'
    ENDCASE

Write pseudocode with the same functionality without using a CASE structure.

### (a) An algorithm will: <span class="part-marks">5 marks</span> - output **each** integer value between 100 and 200 that ends with the digit 7, for example, 107 - output a final count of the number of values that are output. Write pseudocode for this algorithm. Any variables used must be declared. ### (b) Study the following pseudocode. <span class="part-marks">4 marks</span> ``` CASE OF MySwitch 1: ThisChar 'a' 2: ThisChar 'y' 3: ThisChar '7' OTHERWISE: ThisChar '*' ENDCASE ``` Write pseudocode with the same functionality **without** using a `CASE` structure.
Show mark scheme

6(a) [4 marks]

Simple Solution: DECLARE ThisInt, Count : INTEGER  Count 0  FOR ThisInt 100 TO 200 IF ThisInt MOD 10 = 7 THEN OUTPUT ThisInt  Count Count + 1 ENDIF NEXT ThisInt OUTPUT Count Mark as follows: 1 Declare loop variable and counter as integers, counter initialised 2 Loop 100 to 200, no step defined 3 Test value in a loop 4 Output selected value and incrementing a counter in a loop 5 Output the counter, following a reasonable attempt, after the loop Alternative Solution: DECLARE ThisInt, Count : INTEGER  Count 0  FOR ThisInt 107 TO 197 STEP 10 OUTPUT ThisInt  Count Count + 1 NEXT ThisInt OUTPUT Count Mark as follows: 1 Declare loop variable and counter as integers, , counter initialised 2 Loop (107 to 197) 3 STEP 10 or explicit increment if conditional loop used 4 Output each value and incrementing a counter in a loop 5 Output the counter, following a reasonable attempt, after the loop IF MySwitch = 1 THEN

6(b) [7 marks]

 ThisChar 'a' ELSE IF MySwitch = 2 THEN  ThisChar 'y' ELSE IF MySwitch = 3 THEN  ThisChar '7' ELSE  * ThisChar ' ' ENDIF ENDIF ENDIF Mark as follows: 1. ANY test of = 1, 2 or 3 MySwitch 2. All three comparisons and corresponding assignments 3. or initial assignment of default value OTHERWISE, 4. Completely correct syntax IF...THEN...ELSE...ENDIF FUNCTION IsPalindrome(InString : STRING) RETURNS BOOLEAN

Q7
May/Jun 2022 Paper 2 v1

A string is a palindrome if it reads the same forwards as backwards.

The following strings are examples of palindromes:

"Racecar" "madam" "12344321"

Upper-case and lower-case characters need to be treated the same. For example, 'A' is equivalent to 'a'.

(a) A function IsPalindrome() will take a string parameter. The function will return TRUE if the string is a palindrome and will return FALSE if the string is not a palindrome. 7 marks

Write pseudocode for IsPalindrome() .

(b) Strings may consist of several words separated by spaces. 4 marks

For example, the string "never odd or even" becomes a palindrome if the spaces are removed.

The program flowchart represents an algorithm to produce a string OutString by removing all spaces from a string InString .

Set Index to 1

Complete the table by writing the text that should replace each of the labels B, C, D, F and G .

Note: the text may be written as a pseudocode statement.

Label Text
A SetOutString to""
B
C
D
E SetIndex toIndex + 1
F
G
A string is a palindrome if it reads the same forwards as backwards. The following strings are examples of palindromes: "Racecar" "madam" "12344321" Upper-case and lower-case characters need to be treated the same. For example, 'A' is equivalent to 'a'. ### (a) A function `IsPalindrome()` will take a string parameter. The function will return `TRUE` if the string is a palindrome and will return `FALSE` if the string is not a palindrome. <span class="part-marks">7 marks</span> Write pseudocode for `IsPalindrome()` . ### (b) Strings may consist of several words separated by spaces. <span class="part-marks">4 marks</span> For example, the string "never odd or even" becomes a palindrome if the spaces are removed. The program flowchart represents an algorithm to produce a string `OutString` by removing all spaces from a string `InString` . ![](../images/s22_21_q7_fig1.png) |Set Index to 1|| |---|---| ||| ![](../images/s22_21_q7_fig2.png) Complete the table by writing the text that should replace each of the labels **B**, **C**, **D**, **F** and **G** . Note: the text may be written as a pseudocode statement. |Label|Text| |---|---| |**A**|Set`OutString` to`""`| |**B**|| |**C**|| |**D**|| |**E**|Set`Index` to`Index + 1`| |**F**|| |**G**||
Show mark scheme

7(a)

DECLARE IsPal : BOOLEAN DECLARE Index, Num : INTEGER DECLARE CharA, CharB : CHAR  IsPal TRUE  Index 1  Num INT(LENGTH(InString) / 2) WHILE Index <= Num AND IsPal = TRUE  CharA MID(InString, Index, 1)  CharB MID(Instring, LENGTH(Instring) – Index + 1, 1) IF UCASE(CharA) <> UCASE(CharB) THEN  IsPal FALSE // RETURN FALSE ENDIF  Index Index + 1 ENDWHILE RETURN IsPal // RETURN TRUE ENDFUNCTION Mark as follows: 1 Functions header including parameter, ending and return type 2 Calculation of number of pairs to match (length or half length) 3 Loop for half or whole string 4 …Extracting characters to compare // create reverse string 5 Convert characters to same case 6 Check for mismatch of characters inside loop / test for mismatch after loop for reversed string 7 Returning Boolean in both cases

7(b) [6 marks]

Label Text Set to A OutString "" Is B Index > LENGTH(InString)? Is

? C MID(InString, Index, 1) " " Set to OutString OutString & MID(InString, Index, D 1) Set to E Index Index + 1 F YES Mark for each of:  B  D  C  ...F and G Note : The mark for F and G is dependent on a reasonable attempt at C FUNCTION RandomChar() RETURNS CHAR

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

Q6
May/Jun 2022 Paper 2 v2

A string represents a series of whole numbers, separated by commas.

For example:

"12,13,451,22"

Assume that:

  • the comma character ',' is used as a separator

  • the string contains only the characters '0' to '9' and the comma character ','.

A procedure Parse will:

  • take the string as a parameter

  • extract each number in turn

  • calculate the total value and average value of all the numbers

  • output the total and average values with a suitable message.

Write pseudocode for the procedure.

  PROCEDURE Parse(InString : STRING)

ENDPROCEDURE [7]

A string represents a series of whole numbers, separated by commas. For example: "12,13,451,22" Assume that: - the comma character ',' is used as a separator - the string contains only the characters '0' to '9' and the comma character ','. A procedure `Parse` will: - take the string as a parameter - extract each number in turn - calculate the total value and average value of all the numbers - output the total and average values with a suitable message. Write pseudocode for the procedure. ``` PROCEDURE Parse(InString : STRING) ``` `ENDPROCEDURE` [7]
Show mark scheme

6 Three groups of four characters generated correctly with hyphens and without duplication (completely working algorithm)

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

Q1
May/Jun 2022 Paper 2 v3

(a) The following table contains pseudocode examples. 5 marks

Each example may include all or part of:

  • selection

  • iteration (repetition)

  • assignment.

Complete the table by placing one or more ticks (✓ ✓) in each row w.
Pseudocode example Selection Iteration Assignment
FOR Index
1 TO 3
Safe[Index]
GetResult()
NEXT Index

OTHERWISE : OUTPUT "ERROR 1202"
REPEAT UNTIL Index = 27
INPUT MyName
IF Mark > 74 THEN
Grade
'A'
ENDIF
(b) (i) Program variables have values as follows: 2 marks
Variable Value
AAA TRUE
BBB FALSE
Count 99

Complete the table by evaluating each expression.

Expression Evaluation
AAA AND (Count > 99)
AAA AND (NOT BBB)
(Count <= 99) AND (AAA OR BBB)
(BBB AND Count > 50) OR NOT AAA

(ii) Give an example of when a variable of type Boolean would be used. 1 mark

### (a) The following table contains pseudocode examples. <span class="part-marks">5 marks</span> Each example may include all or part of: - selection - iteration (repetition) - assignment. |Complete the table by placing one or more ticks (✓|✓) in each row|w.|| |---|---|---|---| |**Pseudocode example**|**Selection**|**Iteration**|**Assignment**| |`FOR Index`<br>` 1 TO 3`<br>` Safe[Index]`<br>` GetResult()`<br>`NEXT Index`|||| |<br>`OTHERWISE : OUTPUT "ERROR 1202"`|||| |`REPEAT UNTIL Index = 27`|||| |`INPUT MyName`|||| |`IF Mark > 74 THEN`<br>` Grade`<br>` 'A'`<br>`ENDIF`|||| **(b) (i)** Program variables have values as follows: <span class="part-marks">2 marks</span> |Variable|Value| |---|---| |`AAA`|`TRUE`| |`BBB`|`FALSE`| |`Count`|`99`| Complete the table by evaluating each expression. |Expression|Evaluation| |---|---| |`AAA AND (Count > 99)`|| |`AAA AND (NOT BBB)`|| |`(Count <= 99) AND (AAA OR BBB)`|| |`(BBB AND Count > 50) OR NOT AAA`|| #### (ii) Give an example of when a variable of type Boolean would be used. <span class="part-marks">1 mark</span>
Show mark scheme

1(a) [5 marks]

One mark per row

1(b)(i) [2 marks]

1 mark for any two rows correct 1 mark for all rows correct

1(b)(ii) [4 marks]

One mark from:  To terminate a (conditional) loop when a value has been found  When the variable can take only one of two possible values  (Accept by example): When a variable is recording when an action has been done e.g. Yes or No // light is on

Q6
May/Jun 2022 Paper 2 v3

(a) The factorial of a number is the product of all the integers from 1 to that number. 6 marks

For example:

factorial of 5 is given by 1 × 2 × 3 × 4 × 5 = 120 factorial of 7 is given by 1 × 2 × 3 × 4 × 5 × 6 × 7 = 5040 factorial of 1 = 1

Note: factorial of 0 = 1

A function Factorial() will:

  • be called with an integer number as a parameter

  • calculate and return the factorial of the number

  • return −1 if the number is negative.

Write pseudocode for the function Factorial() .

### (a) The factorial of a number is the product of all the integers from 1 to that number. <span class="part-marks">6 marks</span> For example: factorial of 5 is given by 1 × 2 × 3 × 4 × 5 = 120 factorial of 7 is given by 1 × 2 × 3 × 4 × 5 × 6 × 7 = 5040 factorial of 1 = 1 Note: factorial of 0 = 1 A function `Factorial()` will: - be called with an integer number as a parameter - calculate and return the factorial of the number - return −1 if the number is negative. Write pseudocode for the function `Factorial()` .
Show mark scheme

6(a)

DECLARE Value : INTEGER IF ThisNum < 0 THEN  Value -1 ELSE  Value 1 WHILE ThisNum <> 0  Value Value * ThisNum  ThisNum ThisNum – 1 ENDWHILE ENDIF RETURN Value ENDFUNCTION Marks as follows to Max 6 : 1 Function heading and ending including parameter and return value 2 Declaration and initialisation (to 1) of local Integer for result Value 3 Check for illegal value (< 0) 4 (Conditional) loop while not zero // loop for iterations ThisNum ThisNum 5 Attempt to form answer by successive multiplication 6 Completely correct MP5 7 Return value correctly in both cases: < 0 and >= 0 INTEGER ThisNum ALTERNATIVE RECURSIVE SOLUTION: FUNCTION Factorial(ThisNum : INTEGER) RETURNS INTEGER IF ThisNum > 1 THEN * RETURN ThisNum Factorial(ThisNum – 1) ELSE IF ThisNum = 1 OR ThisNum = 0 THEN RETURN 1 ELSE RETURN -1 ENDIF ENDIF ENDFUNCTION Marks as follows: 1 Function heading and ending including parameter and return value 2 Test for ThisNum > 1 3 and if so return product of and Thisnum Factorial(ThisNum-1) 4 Check for special case... 5 ...return 1 for 0 and 1 and return −1 for negative values 6 Return value (correctly in all cases) INTEGER

6(b) [4 marks]

One mark for:  Rows A, B AND C  Each of rows D, E and F Label Text Is

9? A Num B YES Set < to D Identifier Factorial(Num) OUTPUT "Factorial of ", , " is ", <

E Num Identifier Set to // Increment F Num Num + 1 Num

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)

Q5
Oct/Nov 2021 Paper 2 v1
Show mark scheme

5(a) [2 marks]

One mark for the character and one for the corresponding reason. Character: Any except alphabetic, numeric, ',' ':' or space • Reason: character doesn't occur in data to be recorded •

5(b) [7 marks]

Design

5(c) [5 marks]

FUNCTION LogEvents(StudentID : STRING) RETURNS INTEGER DECLARE FileData : STRING DECLARE Index, Count : INTEGER CONSTANT LogFile = "LogFile" ← Count 0 OPENFILE LogFile FOR APPEND ← FOR Index 1 TO 2000 ← FileData LogArray[Index] IF LEFT(FileData, 6) = StudentID THEN WRITEFILE (LogFile, FileData) //brackets optional ← Count Count + 1 ← LogArray[Index] // clear the element "" ENDIF NEXT Index CLOSEFILE LogFile RETURN Count ENDFUNCTION 1 mark for each of the following: 1 Function heading and ending including parameter and return type 2 file for and subsequent OPEN LogFile APPEND CLOSE 3 Loop for 2000 iterations 4 Extract first 6 characters from array element in a loop 5 Compare first 6 characters with parameter in a loop 6 If equal: write whole array element string to file and • increment and • Count clear array element in a loop • 7 Return Count (must have been declared and initialised)

Q1
Oct/Nov 2021 Paper 2 v2

(a) A programmer applies decomposition to a problem that she has been asked to solve. 2 marks

Describe decomposition.

(b) The following pseudocode assigns a value to an element of an array: 3 marks

ThisArray[n]  42
# ←

Complete the following table by writing the answer for each row.

Answer
The number of dimensions ofThisArray
The technical terms for minimum and
maximum values that the variablen may take
The technical term for the variablen in the
pseudocode statement

(c) Complete the pseudocode expressions so that they evaluate to the values shown. 4 marks

Any functions and operators used must be defined in the insert.
Expression Evaluates to
______ ('C') 67
2 *______ ("27") 54
(27 /) 13
"Sub" & ("Abstraction",, ______) "Subtract"
### (a) A programmer applies decomposition to a problem that she has been asked to solve. <span class="part-marks">2 marks</span> Describe decomposition. ### (b) The following pseudocode assigns a value to an element of an array: <span class="part-marks">3 marks</span> ``` ThisArray[n] 42 # ← ``` Complete the following table by writing the answer for each row. ||Answer| |---|---| |The number of dimensions of`ThisArray`|| |The technical terms for minimum and<br>maximum values that the variable`n` may take|| |The technical term for the variable`n` in the<br>pseudocode statement|| ### (c) Complete the pseudocode expressions so that they evaluate to the values shown. <span class="part-marks">4 marks</span> |Any functions and operators used must be defined in the insert.|| |---|---| |**Expression**|**Evaluates to**| |______` ('C')`|`67`| |`2 *`______` ("27")`|`54`| |______` (27 /`______`)`|`13`| |`"Sub" &`______` ("Abstraction",`______, ______`)`|`"Subtract"`|
Show mark scheme

1(a)

The process involves: 1 Breaking down a problem / task into sub problems / steps / smaller parts 2 In order to explain / understand // easier to solve the problem 3 Leading to the concept of program modules // assigning problem parts to teams Max 2

1(b) [4 marks]

The number of dimensions of 1 ThisArray The technical terms for minimum and Lower bound, upper bound maximum values that variable may take n The technical term for the variable in the Index / Subscript n pseudocode expression. One mark per row

1(c) [2 marks]

Expression Evaluates to ('C') 67 ASC 2 * ("27") 54 STR_TO_NUM (27 / ) 13 INT 2 "Sub" & ("Abstraction" , , ) "Subtract" MID 4 5 One mark per row Function names must be exactly as shown

1(d)

Expression Evaluates to FALSE PressureOK AND HiFlow TRUE PumpOn OR PressureOK TRUE NOT PumpOn OR (PressureOK AND NOT HiFlow) FALSE NOT (PumpOn OR PressureOK) AND NOT HiFlow 1 mark for any two rows correct 2 marks for all rows correct.

Q5
Oct/Nov 2021 Paper 2 v3
Show mark scheme

5(a) [2 marks]

One mark for the character and one for the corresponding reason. Character: Any except alphabetic, numeric, ',' ':' or space • Reason: character doesn't occur in data to be recorded •

5(b) [7 marks]

Design

5(c) [5 marks]

FUNCTION LogEvents(StudentID : STRING) RETURNS INTEGER DECLARE FileData : STRING DECLARE Index, Count : INTEGER CONSTANT LogFile = "LogFile" ← Count 0 OPENFILE LogFile FOR APPEND ← FOR Index 1 TO 2000 ← FileData LogArray[Index] IF LEFT(FileData, 6) = StudentID THEN WRITEFILE (LogFile, FileData) //brackets optional ← Count Count + 1 ← LogArray[Index] // clear the element "" ENDIF NEXT Index CLOSEFILE LogFile RETURN Count ENDFUNCTION 1 mark for each of the following: 1 Function heading and ending including parameter and return type 2 file for and subsequent OPEN LogFile APPEND CLOSE 3 Loop for 2000 iterations 4 Extract first 6 characters from array element in a loop 5 Compare first 6 characters with parameter in a loop 6 If equal: write whole array element string to file and • increment and • Count clear array element in a loop • 7 Return Count (must have been declared and initialised)

Q1
May/Jun 2021 Paper 2 v1

(a) A program is being developed to help manage the membership of a football club. 4 marks

Complete the following identifier table.

Example
value
Explanation Variable name Data type
"Wong" The preferred name of the member
joining the football club
FALSE A value to indicate whether an
existing member of the club lives at
the same address
19/02/1983 When the member joined the football
club
1345 The number of points a member has
earned. Members of the club earn
points for different activities.

(b) Each pseudocode statement in the following table may contain an error due to the incorrect use of the function or operator. 5 marks

Describe the error in each case, or write ‘NO ERROR’ if the statement contains no error.

You can assume that none of the variables referenced are of an incorrect type.

Statement Error
Result
2 & 4
SubString
MID("pseudocode", 4, 1)
IF x = 3 OR 4 THEN
Result
Status AND INT(x/2)
Message
"Done" + LENGTH(MyString)
### (a) A program is being developed to help manage the membership of a football club. <span class="part-marks">4 marks</span> Complete the following identifier table. |Example<br>value|Explanation|Variable name|Data type| |---|---|---|---| |`"Wong"`|The preferred name of the member<br>joining the football club||| |`FALSE`|A value to indicate whether an<br>existing member of the club lives at<br>the same address||| |`19/02/1983`|When the member joined the football<br>club||| |`1345`|The number of points a member has<br>earned. Members of the club earn<br>points for different activities.||| ### (b) Each pseudocode statement in the following table may contain an error due to the incorrect use of the function or operator. <span class="part-marks">5 marks</span> Describe the error in each case, or write ‘NO ERROR’ if the statement contains no error. You can assume that none of the variables referenced are of an incorrect type. |Statement|Error| |---|---| |`Result`<br>` 2 & 4`|| |`SubString`<br>` MID("pseudocode", 4, 1)`|| |`IF x = 3 OR 4 THEN`|| |`Result`<br>` Status AND INT(x/2)`|| |`Message`<br>` "Done" + LENGTH(MyString)`||
Show mark scheme

1(a)

Example Explanation Variable name Data type value The preferred name of the "Wong" MemberName STRING member joining the football club A value to indicate FALSE FamilyMember BOOLEAN whether an existing member of the club lives at the same address When the member joined 19/02/1983 StartDate DATE the football club The number of points a 1345 Points INTEGER member has earned. Members of the club earn points for different activities. One mark for each appropriate variable name plus data type

1(b) [3 marks]

Statement Error Should be arithmetic operator (not &) // 2 and 4 ← Result 2 & 4 should be CHAR / STRING NO ERROR ← SubString MID("pseudocode", 4, 1) Not Boolean values / incorrect operator // IF x = 3 OR 4 THEN Condition incorrect doesn't evaluate INT(X/2) to a boolean value / ← Result Status AND INT(X/2) incorrect operator Can’t add string to number / ← Message "Done" + LENGTH(MyString) is not a number "Done" One mark for each row

1(c) [5 marks]

Structure: Record • Justification: Allows different data types • to be stored under one identifier • Mark as follows: One mark for Structure Two marks for justification. Alternative Two (1D) arrays • One of string, one of integer • Where same index links the name with the score •

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

Q6
May/Jun 2021 Paper 2 v2

A procedure CountVowels() will:

  • be called with a string containing alphanumeric characters as its parameter

  • count and output the number of occurrences of each vowel (a, e, i, o, u) in the string

  • count and output the number of occurrences of the other alphabetic characters (as a single total).

The string may contain both upper and lower case characters.

Each count value will be stored in a unique element of a global 1D array CharCount of type INTEGER . The array will contain six elements.

Write pseudocode for the procedure CountVowels() . 8 marks

A procedure `CountVowels()` will: - be called with a string containing alphanumeric characters as its parameter - count and output the number of occurrences of each vowel (a, e, i, o, u) in the string - count and output the number of occurrences of the other alphabetic characters (as a single total). The string may contain both upper and lower case characters. Each count value will be stored in a unique element of a global 1D array `CharCount` of type `INTEGER` . The array will contain six elements. Write pseudocode for the procedure `CountVowels()` . <span class="part-marks">8 marks</span>
Show mark scheme

6 [3 marks]

PROCEDURE CountVowels(ThisString : STRING) DECLARE Index : INTEGER DECLARE ThisChar : CHAR ← FOR Index 1 to 6 ← CharCount[Index] 0 //initialise elements NEXT Index ← Index 1 ← FOR Index 1 TO LENGTH(ThisString) ← ThisChar LCASE(MID(ThisString, Index, 1)) CASE OF ThisChar ← 'a' : CharCount[1] CharCount[1] + 1 ← 'e' : CharCount[2] CharCount[2] + 1 ← 'i' : CharCount[3] CharCount[3] + 1 ← 'o' : CharCount[4] CharCount[4] + 1 ← 'u' : CharCount[5] CharCount[5] + 1 ← 'a' TO 'z': CharCount[6] CharCount[6] + 1 ENDCASE NEXT Index ← FOR Index 1 to 6 OUTPUT CharCount[Index] //output results NEXT Index ENDPROCEDURE 1 mark for each of the following: 1 Procedure heading (with parameter) and ending 2 Declare local variable for as loop counter but not Index CharCount array 3 Initialise elements of array to zero CharCount 4 Loop through all characters in ThisString 5 Use of to extract single character MID() 6 Test for each vowel and increment associated count 7 Test for consonants and increment associated count 8 Output the results (supporting text not necessary) after the loop Note: Max 7 if not used to store count CharCount

Q7
May/Jun 2021 Paper 2 v2

A procedure, FormatName() :

  • is called with a string containing words and spaces as its parameter. In this context, a word is any sequence of characters that does not contain a space character.

  • creates a new formatted string from this string with the following requirements:

  1. Any leading spaces removed (spaces before the first word).
  2. Any trailing spaces removed (spaces after the last word).
  3. Any multiple spaces between words converted to a single space.
  4. All characters converted to lower case.

The FormatName() procedure has been written in a programming language and is to be tested using the black-box method.

(a) Give a test string that could be used to show that all four formatting requirements have been applied correctly. 3 marks

Use the symbol ‘ ∇ ’ to represent a space character.

(b) The FormatName() procedure should assign a value to the global variable FString . 2 marks

There is a fault in the program, which means that the assignment does not always take place.

Explain two ways of exposing the fault.

A procedure, `FormatName()` : - is called with a string containing words and spaces as its parameter. In this context, a word is any sequence of characters that does not contain a space character. - creates a new formatted string from this string with the following requirements: 1. Any leading spaces removed (spaces before the first word). 2. Any trailing spaces removed (spaces after the last word). 3. Any multiple spaces between words converted to a single space. 4. All characters converted to lower case. The `FormatName()` procedure has been written in a programming language and is to be tested using the black-box method. ### (a) Give a test string that could be used to show that all **four** formatting requirements have been applied correctly. <span class="part-marks">3 marks</span> Use the symbol ‘ ∇ ’ to represent a space character. ### (b) The `FormatName()` procedure should assign a value to the global variable `FString` . <span class="part-marks">2 marks</span> There is a fault in the program, which means that the assignment does not always take place. Explain **two** ways of exposing the fault.
Show mark scheme

7(a)

Test string should contain: At least one leading space (before the first word) • at least one trailing space (after the last word) • at least one instance of multiple spaces between words • At least one upper case character • Mark as follows: One mark for one correct Two marks for three correct Three marks for all correct

7(b) [5 marks]

One mark for each: Dry run / produce a trace table / walk through the code • Add output statements to allow the code to be tracked • Insert a Breakpoint into the program // use single-stepping to execute • instructions // monitor variables using a watch window Try different test values to see which ones fail • Note: Max 2 marks

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

Q1
May/Jun 2021 Paper 2 v3

(a) A program is being developed to help manage the membership of a football club. 4 marks

Complete the following identifier table.

Example
value
Explanation Variable name Data type
"Wong" The preferred name of the member
joining the football club
FALSE A value to indicate whether an
existing member of the club lives at
the same address
19/02/1983 When the member joined the football
club
1345 The number of points a member has
earned. Members of the club earn
points for different activities.

(b) Each pseudocode statement in the following table may contain an error due to the incorrect use of the function or operator. 5 marks

Describe the error in each case, or write ‘NO ERROR’ if the statement contains no error.

You can assume that none of the variables referenced are of an incorrect type.

Statement Error
Result
2 & 4
SubString
MID("pseudocode", 4, 1)
IF x = 3 OR 4 THEN
Result
Status AND INT(x/2)
Message
"Done" + LENGTH(MyString)
### (a) A program is being developed to help manage the membership of a football club. <span class="part-marks">4 marks</span> Complete the following identifier table. |Example<br>value|Explanation|Variable name|Data type| |---|---|---|---| |`"Wong"`|The preferred name of the member<br>joining the football club||| |`FALSE`|A value to indicate whether an<br>existing member of the club lives at<br>the same address||| |`19/02/1983`|When the member joined the football<br>club||| |`1345`|The number of points a member has<br>earned. Members of the club earn<br>points for different activities.||| ### (b) Each pseudocode statement in the following table may contain an error due to the incorrect use of the function or operator. <span class="part-marks">5 marks</span> Describe the error in each case, or write ‘NO ERROR’ if the statement contains no error. You can assume that none of the variables referenced are of an incorrect type. |Statement|Error| |---|---| |`Result`<br>` 2 & 4`|| |`SubString`<br>` MID("pseudocode", 4, 1)`|| |`IF x = 3 OR 4 THEN`|| |`Result`<br>` Status AND INT(x/2)`|| |`Message`<br>` "Done" + LENGTH(MyString)`||
Show mark scheme

1(a)

Example Explanation Variable name Data type value The preferred name of the "Wong" MemberName STRING member joining the football club A value to indicate FALSE FamilyMember BOOLEAN whether an existing member of the club lives at the same address When the member joined 19/02/1983 StartDate DATE the football club The number of points a 1345 Points INTEGER member has earned. Members of the club earn points for different activities. One mark for each appropriate variable name plus data type

1(b) [3 marks]

Statement Error Should be arithmetic operator (not &) // 2 and 4 ← Result 2 & 4 should be CHAR / STRING NO ERROR ← SubString MID("pseudocode", 4, 1) Not Boolean values / incorrect operator // IF x = 3 OR 4 THEN Condition incorrect doesn't evaluate INT(X/2) to a boolean value / ← Result Status AND INT(X/2) incorrect operator Can’t add string to number / ← Message "Done" + LENGTH(MyString) is not a number "Done" One mark for each row

1(c) [5 marks]

Structure: Record • Justification: Allows different data types • to be stored under one identifier • Mark as follows: One mark for Structure Two marks for justification. Alternative Two (1D) arrays • One of string, one of integer • Where same index links the name with the score •

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