11.2 Constructs
AS Level · 68 questions found
What this topic covers
Section titled “What this topic covers”- IF…ELSE and nested IF statements; CASE structure
- Count-controlled loop (FOR), pre-condition (WHILE), post-condition (REPEAT)
- Justify which loop structure best suits a given problem
Past paper questions
Section titled “Past paper questions”A program contains a global 1D array Number consisting of 20 elements of type REAL
A procedure Store() will input a sequence of up to 20 real values, one value at a time. These values will be assigned to elements of the array using four steps:
Step 1: store the first value in the sequence in the first element of the array Step 2: check each subsequent value input. If this value is larger than the previous value input, then assign the value to the next array element, otherwise go to step 4 Step 3: repeat from step 2 unless the array is full Step 4: output the count of the number of values stored in the array together with a suitable message.
(a) Complete the pseudocode for Store() 6 marks
All variables used in the algorithm must be declared.
PROCEDURE Store()
ENDPROCEDURE
(b) The requirements of the program change:
the number of values in the sequence is unknown, but may be higher than 20
the values will need to be accessed by another program as data.
The data will be stored in a text file instead of an array.
(i) Give two benefits of using a text file instead of an array. 2 marks
1
2
(ii) State any change that will need to be made before each value is written to the file. 1 mark
Show mark scheme
4(a)
Alternative FOR loop example solution: PROCEDURE Store() DECLARE ThisNum, LastNum : REAL DECLARE Index : INTEGER // index to global array DECLARE Count : INTEGER INPUT ThisNum LastNum ThisNum Number[1] ThisNum Count 1 INPUT ThisNum FOR Index 2 TO 20 IF ThisNum > LastNum THEN Number[Index] ThisNum LastNum ThisNum Count Count + 1 IF Index < 20 THEN INPUT ThisNum ENDIF ELSE BREAK ENDIF NEXT Index OUTPUT Count, " values were stored in the array" ENDPROCEDURE Alternative loop: Count 1 INPUT ThisNum FOR Index 2 TO 20 IF ThisNum > Number[Index - 1] THEN Number[Index] ThisNum Count Count + 1 IF Index < 20 THEN INPUT ThisNum ENDIF ELSE BREAK ENDIF NEXT Index Mark as follows: 1 Declare local variables as integer, and as real Index ThisNum LastNum 2 Input value and assign to first element 3 Count-controlled loop 4 Count-controlled loop with BREAK if current value greater than previous value 5 ... Assign input value to current element following correct comparison in a loop 6 Final output giving count of elements stored plus message following a reasonable attempt after loop
4(b)(i) [2 marks]
One mark per point: 1 The amount of values stored (in a text file) is not fixed / not limited (other than by secondary storage available) // The amount values stored is not limited to the size of the array 2 The data is stored permanently / non-volatile // Data can be restored / reused without re-entering values
4(b)(ii) [1 mark]
Each (real) value would have to be converted to a string
(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) |
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
A quiz has nine questions. There are:
five easy questions each worth 3 points
four hard questions each worth 5 points.
At the end of the quiz the points for each correctly answered question are added to give a total score.
A check is made to test that the total score is valid using a 1D array CheckTotal of type BOOLEAN. Each index value of the array represents a possible total score. The corresponding element value is TRUE if the index value represents a valid total score and FALSE otherwise.
The first nine rows of the array are:
| Index value |
Element value |
Comment |
|---|---|---|
| 0 | TRUE | valid total score (no correct answers) |
| 1 | FALSE | invalid total score |
| 2 | FALSE | invalid total score |
| 3 | TRUE | valid total score (one 3-point question correct) |
| 4 | FALSE | invalid total score |
| 5 | TRUE | valid total score (one 5-point question correct) |
| 6 | TRUE | valid total score (two 3-point questions correct) |
| 7 | FALSE | invalid total score |
| 8 | TRUE | valid total score (one 3-point question and one 5-point question correct) |
For example, a total score of 6 points is valid; the value of the array element at index value 6 is TRUE
(a) Write pseudocode to declare CheckTotal and to set all elements of the array to FALSE All variables used must be declared. 4 marks
(b) The pseudocode represents an algorithm to set the appropriate elements of the array to TRUE Complete the pseudocode: 5 marks
DECLARE EasyQ, HardQ : INTEGER
FOR EasyQ ______ TO 15 STEP
FOR HardQ 0 TO ______ STEP
CheckTotal[______] TRUE
NEXT HardQ
NEXT EasyQ
(c) The array elements have been assigned the required values. 4 marks
A module ValidateScore() will take an integer value representing a total score as a parameter. It will return TRUE if the total score is valid, or FALSE if it is not valid.
Describe the algorithm for ValidateScore() using four steps.
Do not use pseudocode in your answer.
Step 1
Step 2
Step 3
Step 4
Show mark scheme
4(a) [4 marks]
Example solution: DECLARE CheckTotal : ARRAY [0:35] OF BOOLEAN DECLARE Index : INTEGER FOR Index 0 TO 35 CheckTotal[Index] FALSE NEXT Index Mark as follows: MP1 Declaration of array CheckTotal MP2 Declaration of a loop counter MP3 Loop – with correct syntax and number of iterations MP4 Assignment of array element to FALSE
4(b) [5 marks]
DECLARE EasyQ, HardQ : INTEGER 0 3 FOR EasyQ TO 15 STEP MP1 MP2 20 5 FOR HardQ 0 TO STEP MP3 MP4 HardQ + EasyQ CheckTotal[ ] TRUE MP5 NEXT HardQ NEXT EasyQ Mark as follows: One mark per gap (boldened)
4(c) [4 marks]
MP1 Check that the parameter value is in the range 0 to 35 MP2 ... and if not, return FALSE MP3 Use the parameter value as the index to array CheckTotal MP4 Return the value from given index position
A string function Compare() will compare two strings.
The function will:
take four parameters:
two strings, String1 and String2
a character, Position, to indicate whether String1 will be compared with the start ('s'), or the end ('e') of String2
a Boolean, CaseMatters, to indicate whether an upper case character and lower case character (for example, 'A' and 'a') are regarded as different (TRUE), or as the same (FALSE)
return FALSE if String2 has fewer characters than String1
return TRUE if the comparison is true, otherwise return FALSE
For example:
| Parameter | |||
|---|---|---|---|
| String1 | String2 | CaseMatters | Position |
| "Cat" | "Catalogue" | TRUE | 's' |
| "CAT" | "Catalogue" | TRUE | 's' |
| "CAT" | "Catalogue" | FALSE | 's' |
| "Cat" | "Catalogue" | TRUE | 'e' |
| "GUE" | "Catalogue" | FALSE | 'e' |
| "Catalogue" | "Cat" | TRUE | 's' |
Return value
TRUE
FALSE
TRUE
FALSE
TRUE
FALSE
Write pseudocode for the function Compare() 7 marks
Show mark scheme
6 [7 marks]
Example solution: FUNCTION Compare(String1, String2 : STRING, __ CaseMatters : BOOLEAN, Position : CHAR) RETURNS BOOLEAN DECLARE S1Length : INTEGER S1Length LENGTH(String1) IF LENGTH(String2) < S1Length THEN RETURN FALSE // String2 is shorter than String1 ENDIF IF CaseMatters = FALSE THEN String1 TO_UPPER(String1) String2 TO_UPPER(String2) ENDIF CASE Position 'e' : String2 RIGHT(String2, S1Length) 's' : String2 LEFT(String2, S1Length) ENDCASE IF String1 = String2 THEN RETURN TRUE ELSE RETURN FALSE ENDIF ENDFUNCTION Mark as follows: MP1 Function heading and parameters and ending and return type MP2 Calculate length of String1 MP3 if is shorter than , return String2 String1 FALSE MP4 Compare (modified) strings MP5 Test
- if and convert two string(s) to same CaseMatters FALSE case MP6 Test for the value of ‘s’/’e’ and form modified string(s) in one or both cases MP7 Return appropriate value in all cases BOOLEAN
A program contains a global 1D array Data containing 20 elements of type INTEGER
A global string NumString represents a sequence of three-digit numbers, separated by commas. For example:
"101,456,219,754,328"
The string contains at least four three-digit numbers. The total number of three-digit numbers in the string is unknown.
A procedure Store() will:
extract one three-digit number at a time from NumString
convert each of the three-digit numbers extracted to an integer and assign this to the next array element, starting from index 1
end when all three-digit numbers have been stored, or when the array is full.
Complete the pseudocode for Store()
All local variables used must be declared.
PROCEDURE Store()
ENDPROCEDURE 6 marks
Show mark scheme
4 Alternative Solution extracting one character at a time and testing for comma PROCEDURE Store()
DECLARE Index, Position : INTEGER DECLARE SubString : STRING Decalre ThisCharacter : CHAR Index 1 Position 0 SubString "" WHILE Index <= 20 AND Position <= LENGTH(NumString) Charcter MID(NumString, Position, 1) IF Character = ',' Data[Index] STR_TO_NUM(SubString) Index Index + 1 SubString "" ELSE SubString SubString & Character ENDIF Position Position + 1 ENDWHILE Data[Index] STR_TO_NUM(SubString) //last 3 digit string ENDPROCEDURE Mark as follows: 1 Declare all variables used 2 Conditional loop while end of string not reached 3 ... and array not full 4 Correct extraction and use of a character from in a loop NumString 5 Test for comma in a loop 6 If true convert substring to number … and store in array and set to and increment Data SubString "" Index 7 Otherwise concatenate next character from to end of NumString Substring Max 6
A global 1D array Num of integers contains four elements. A program assigns values to these elements as shown:
Num[1] 1 Num[2] 2 Num[3] 5 Num[4] 3
A procedure Process() manipulates the values in the array.
The procedure is written in pseudocode: PROCEDURE Process(Start : INTEGER) DECLARE CaseVar, Index, Count : INTEGER
Index Start Count 0
WHILE Count <= 20 CaseVar Num[Index] CASE OF CaseVar 1 : Num[Index] Num[Index] + Index //clause one Index Index + 1 Count Count + 1
2 : Num[Index] Num[Index] + Index //clause two Index Index + 2 Count Count + 2
3 : Num[Index] Num[Index] * 2 //clause three Index Index + 3 Count Count - 1
4 : Count Count + 4 //clause four OTHERWISE : Count 20 ENDCASE
Index (Index MOD 4) + 1
ENDWHILE
ENDPROCEDURE
(a) Complete the trace table by dry running the procedure when it is called in the statement: 5 marks
CALL Process(1)
| Index | CaseVar | Count | Num[1] | Num[2] | Num[3] | Num[4] |
|---|---|---|---|---|---|---|
(b) As a reminder, the CASE structure in the pseudocode is:
CASE OF CaseVar 1 : Num[Index] Num[Index] + Index //clause one Index Index + 1 Count Count + 1
2 : Num[Index] Num[Index] + Index //clause two Index Index + 2 Count Count + 2
3 : Num[Index] Num[Index] * 2 //clause three Index Index + 3 Count Count - 1
4 : Count Count + 4 //clause four OTHERWISE : Count 20 ENDCASE
The CASE structure could be optimised by combining two existing clauses.
(i) Identify the CaseVar values for these two existing clauses. 1 mark
(ii) Write pseudocode for a single clause to replace the two clauses identified in (b) (i). 2 marks
Show mark scheme
5(a) [5 marks]
Zone 1 Zone 2 Zone 3 Zone 4 Zone 5 Zones 1 to 4 : One mark for each set of values as shown Zone 5: Num[4] set to 6 when Index is 7 and Num[1] set to 3 when index is 3 for second time
5(b)(i) [1 mark]
1 and 2
5(b)(ii) [2 marks]
1 TO 2 : Num[Index] Num[Index] + Index Index Index + CaseVar Count Count + CaseVar One mark per point: • use of variable rather than literal values CaseVar • completely correct clause
A program is being developed to calculate the pay of employees working for a company.
A function CalculateBonus() calculates bonus pay based on the value of sales.
Bonus pay is calculated as shown in the table.
| Value of sales (in dollars) |
Bonus pay (in dollars) |
|---|---|
| below 2000 | 0 |
| between 2000 and 4000 inclusive | 10 |
| above 4000 | 100 |
A flowchart for the function CalculateBonus() has been designed.

| RETURN BonusPay | |
|---|---|
END
(a) The flowchart contains logic errors.
Show mark scheme
2(a)(i) [1 mark]
The two decision boxes are in the wrong order // The first decision symbol is wrong The first decision should check for values greater than or equal to 2000
2(a)(ii) [1 mark]
Swap around the two decision boxes The first decision box should check for values greater than or equal to 2000 and the second decision box should check for values above 4000
2(b)(ii) [2 marks]
The value cannot be changed // avoids being different in two places Makes the program easier to understand Avoids repeatedly writing the same value throughout the program A change to the value requires a change in only one statement
2(b)(iii) [1 mark]
(The code is) tried and tested so error free Provides functionality / code that the programmer may find difficult to code themselves
2(c) [4 marks]
Syntax (error) Rules of programming language // the language grammar was not followed Run-time (error ) The program performs an illegal operation and one mark for the description
A student has been asked to create a simple guessing game program. This program will generate a random integer value between 1 and 100. It will then repeatedly prompt the user to input an integer value until they input the randomly generated value.
The student has written a structured English description:
step 1 – randomly generate an integer value between 1 and 100 inclusive step 2 – prompt the user to input an integer value step 3 – output an appropriate message if the value input was too high; then repeat from step 2 step 4 – output an appropriate message if the value input was too low; then repeat from step 2 step 5 – output an appropriate message if the value input was the same value that was randomly generated; then end the program.
Write a pseudocode algorithm from this structured English description.
Assume no input validation is needed. 8 marks
Show mark scheme
3 [8 marks]
INT(RAND(100)) + 1 Declare all variables used Uses function RAND() Uses function INT() Correct syntax for random number between 1 and 100 Conditional loop until correct number guessed Prompt and input a guess in a loop Check if guess is too high in a loop Check if guess is too low in a loop Output appropriate message (x2) when the number is not guessed correctly ( in the loop) and output correct guess message
Study the algorithm:
DECLARE Chars : ARRAY[1:4] OF CHAR DECLARE I, J : INTEGER DECLARE Key : CHAR I 2 Chars[1] 'D' Chars[2] 'T' Chars[3] 'H' Chars[4] 'R' WHILE I <= 4 //Outer loop Key Chars[I] J I – 1 WHILE J >= 0 AND Chars[J] > Key //Inner loop Chars[J + 1] Chars[J] J J – 1 ENDWHILE Chars[J + 1] Key I I + 1 ENDWHILE
(a) The outer loop structure used in the algorithm is not the most appropriate one to use. 2 marks
State the type of loop structure that would be the most appropriate to use and justify why it is the most appropriate.
Loop structure
Justification
(b) Complete the trace table by dry running the algorithm. 6 marks
The first row has been completed.
| I | Key | J | Chars[J] | Chars | |||
|---|---|---|---|---|---|---|---|
| I | Key | J | Chars[J] | [1] | [2] | [3] | [4] |
| 2 | 'D' | 'T' | 'H' | 'R' | |||
Show mark scheme
4(a) [2 marks]
Count-controlled The number of iterations required is known
4(b) [6 marks]
Chars I Key J Chars[J] [1] [2] [3] [4] 2 'D' 'T' 'H' 'R' 'D' 'T' 1 MP1 3 'T' 'H' 2 'T' MP2 1 'D' 'H' MP3 4 'R' 3 'T' 'T' (‘R’) 2 'H' MP4 'R' 5 MP5 array final values Chars MP6 'D' 'H' 'R' 'T'
A program to calculate the pay of employees working for a company is being designed.
(a) Stepwise refinement has been used in the design of the program. 2 marks
Describe stepwise refinement.
(b) One of the program modules used to calculate employees’ weekly bonus pay has been completed. The amount of bonus pay they receive is based on the number of hours worked and the value of sales made as shown in the table.
Bonus pay and value of sales are both in dollars.
| Hours worked | Value of sales | Bonus pay |
|---|---|---|
| between 1 and 40 inclusive | 2000 or less | 0 |
| between 1 and 40 inclusive | above 2000 | 50 |
| above 40 | 2000 or less | 10 |
| above 40 | above 2000 | 100 |
(i) The module is tested using white‑box testing. 2 marks
State two tests, using valid data, that can be used to test different paths through the program.
Test one:
Hours worked
Value of sales
Bonus pay
Test two:
Hours worked
Value of sales
Bonus pay
Show mark scheme
2(a) [2 marks]
Mark as follows:
- To increase the level of detail of the algorithm // To break the problem / task into smaller steps …
- … until steps can be directly translated into lines of code // from which it can be programmed
2(b)(i) [2 marks]
One mark for each of set test values Hours worked between 1 and 40 inclusive Sales value = 2000 Bonus Pay: 0 Hours worked above 40 Sales value = 2000 Bonus Pay: 10 Hours worked between 1 and 40 inclusive Sales value 2000 Bonus Pay: 50 Hours worked above 40 Sales value above 2000 Bonus Pay: 100 max 2
2(b)(ii) [2 marks]
One mark per point • Simple modules are written to replace each of the unfinished modules. • Each simple module will return an expected value / will output a message to show it has been called.
2(b)(iii) [2 marks]
One mark for naming type of error and one mark for corresponding description Type of error: Logic (error) Description: Where the program does not behave as expected / Does not give expected result / An error in the logic of the algorithm Or Type of error: Run-time (error) Description: The program performs an illegal operation Max 2
An algorithm is designed to generate and output two unique random integers. Each integer value is between –10 and 10 inclusive.
If both integers output are negative, a third random integer between 30 and 35 inclusive will be generated and output.
Write pseudocode for this algorithm. 8 marks
Show mark scheme
3 [8 marks]
Example solution DECLARE FirstNumber : INTEGER DECLARE SecondNumber : INTEGER DECLARE ThirdNumber : INTEGER FirstNumber INT(RAND(21)) – 10 OUTPUT FirstNumber REPEAT SecondNumber INT(RAND(21)) – 10 UNTIL FirstNumber <> SecondNumber OUTPUT SecondNumber IF FirstNumber < 0 AND SecondNumber < 0 THEN ThirdNumber INT(RAND(6)) + 30 OUTPUT ThirdNumber ENDIF Mark points:
- Declare all variables used
- Use function with any integer parameter RAND()
- Use function with any numeric parameter INT()
- Conditional loop until two different random numbers are generated −
- Use function using random number generated between 10 and 10 INT() inclusive in a loop
- Output two different random integers / numbers
- Check if both random integers / numbers are negative
- then output a (third) random integer / number between 30 and 35 inclusive
A programmer has been asked to create a module RollDice() to simulate multiple rolls of a dice. This module will be used as part of a program for a game.
The module will:
step 1 – take a positive integer parameter representing the number of times the dice will be rolled
step 2 – simulate one roll of the dice by generating a random integer between 1 and 6 inclusive
step 3 – output the integer generated
step 4 – repeat, as required from step 2
step 5 – calculate the average value of the random integers generated
step 6 – return the average value.
Write pseudocode for the module RollDice() 7 marks
Show mark scheme
3 [5 marks]
Example solution : FUNCTION RollDice(NoOfTimes : INTEGER) RETURNS REAL DECLARE RollValue : INTEGER DECLARE Average : REAL DECLARE Count : INTEGER DECLARE Sum : INTEGER Sum 0 FOR Count 1 TO NoOfTimes RollValue INT(RAND(6)) + 1 OUTPUT RollValue Sum Sum + RollValue NEXT Count Average Sum / NoOfTimes RETURN Average ENDFUNCTION MP1 Declare all variables used and initialise to Sum 0 MP2 Loop for ‘number of times’ parameter MP3 Use () function with Integer parameter in a loop RAND MP4 Use () function in a loop INT MP5 Generate a random integer between 1 and 6 in a loop MP6 Output each value generated i n a loop MP7 Calculate and if used check declared as and Sum Average REAL return and check function header returns Average REAL MP1 Open the file ( ) in read mode and subsequently close
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
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
A program uses three global integer variables HH, MM and SS to represent the current time in hours, minutes and seconds using the 24-hour clock notation.
Midnight would be represented as 00:00:00 (HH:MM:SS). If the variables HH, MM and SS contained the values 16, 30 and 10 respectively, then the time would be 16:30:10 or just after 4.30 in the afternoon.
A procedure Tick() will be called every second. The procedure Tick() will:
update the value in SS each time it is called
update the values in HH and MM as appropriate
call a procedure CheckAlarm() at the start of each minute
call a procedure NewDay() whenever the time reaches midnight.
Complete the pseudocode for procedure Tick().
PROCEDURE Tick()
ENDPROCEDURE 6 marks
Show mark scheme
2 [6 marks]
Example solution: PROCEDURE Tick() SS SS + 1 IF SS = 60 THEN SS 0 MM MM + 1 IF MM = 60 THEN MM 0 HH HH + 1 IF HH = 24 THEN HH 0 CALL NewDay() ENDIF ENDIF CALL CheckAlarm() ENDIF ENDPROCEDURE Mark as follows: 1 Increment SS anywhere in the code 2 Call when SS is set to zero CheckAlarm() 3 Test if = 60 anywhere in the code … SS if so: 4 set to 0 SS 5 increment MM 6 When is set to 60 set to 0 and increment 7 When is set to 24 set to 0 and call NewDay() Max 6 marks
A software developer follows a program development life cycle. The life cycle divides the development process into various stages.
(a) The following table lists some development activities. 5 marks
Complete the table by writing the name of the life cycle stage for each activity.
| Activity | Name of life cycle stage |
|---|---|
| The walkthrough method is used. | |
| An algorithm is implemented in a programming language. | |
| The client is interviewed about problems with the current system. | |
| The program is modified to run on new hardware. | |
| Records and file structures are defined. |
(b) The program contains a validation function.
(i) The function will: 4 marks
take an integer value as a parameter
return TRUE if the value is within the range 24 to 37, inclusive
otherwise return FALSE.
Complete the table to define a test plan to thoroughly test the operation of the function.
| Type of test data | Test data value | Expected result |
|---|---|---|
| Normal | 30 | TRUE |
(ii) The function is to be tested on its own. When it is shown to work correctly the function will be combined with other modules and testing will continue. 1 mark
Identify the type of testing that this represents.
Show mark scheme
5(a) [5 marks]
Name of life Activity cycle stage The walkthrough method is used. Testing An algorithm is implemented in a programming language. Coding The client is interviewed about problems with the current Analysis system. The program is modified to run on new hardware. Maintenance Records and file structures are defined. Design One mark per row
5(b)(i) [4 marks]
One mark per row Type of test data Test data value Expected result Abnormal 12 (< 23) FALSE Abnormal / Boundary / Extreme 23 FALSE Boundary / Extreme 24 TRUE Boundary 25 TRUE Boundary 36 TRUE Boundary /Extreme 37 TRUE Abnormal / Boundary / Extreme 38 FALSE Abnormal 99 (> 38) FALSE Max 4 marks
5(b)(ii) [1 mark]
Integration (testing)
A factory produces food items. The items must be used within a certain number of days after their production date. The number of days is known as the shelf life. It is different for each type of item but is always a whole number in the range 1 to 21 (inclusive).
The latest date that an item can be used is called the ‘use-by’ date.
A program is needed to produce labels which show the ‘use-by’ date.
Part of the program is a function GetDate() which will:
take two parameters: a production date and a value representing the shelf life
return the corresponding ‘use-by’ date.
The program contains a global 1D array DaysInMonth of type integer which stores the number of days in each month (index 1 is January):
| Index | Value |
|---|---|
| 1 | 31 |
| 2 | 28 |
| 3 | 31 |
| 4 | 30 |
| 11 | 30 |
| 12 | 31 |
(a) An algorithm uses the array DaysInMonth to calculate a ‘use-by’ date. An alternative design would involve the use of multiple selection statements. 2 marks
An array-based technique is often used when there is a large number of different values to check and where no pattern exists.
One advantage of using an array-based technique is the speed of execution compared to the use of multiple selection statements.
Give two other advantages of using an array for this type of operation rather than a solution based on multiple selection statements.
1
2
(b) Complete the pseudocode for the function GetDate(). 7 marks
Date functions from the insert should be used in your solution.
FUNCTION GetDate(ProductionDate : DATE, ShelfLife : INTEGER) RETURNS DATE
ENDFUNCTION
Show mark scheme
6(a) [2 marks]
One mark per point: 1 Fewer lines of code are needed 2 The program is simpler/ less complex // Program is easier to design / code / maintain / modify / test / debug 3 Direct access to days in a month / data (using month number as index) // Can use index / month to (directly) access days in month / data Max 2 marks
6(b) [7 marks]
Example Solution FUNCTION GetDate(ProductionDate : DATE, ShelfLife : INTEGER) RETURNS DATE DECLARE NewDate : DATE DECLARE DD, MM, YY, LastDay : INTEGER DD DAY(ProductionDate) MM MONTH(ProductionDate) YY YEAR(ProductionDate) DD DD + ShelfLife LastDay DaysInMonth[MM] IF DD > LastDay THEN MM MM + 1 DD DD – LastDay IF MM = 13 THEN MM 1 YY YY + 1 ENDIF ENDIF NewDate SETDATE(DD, MM, YY) RETURN NewDate ENDFUNCTION Mark as follows: 1 Declare three variables of to store , and TYPE INTEGER 2 Correct use of date functions from Insert to extract three integer values representing DD, MM and YY and use/assign to a variable 3 Add parameter to and use / assign result to a variable ShelfLife DD 4 Extract from using as LastDay DaysInMonth MM Index 5 Test for new after end of month / DD DaysInMonth[MM] … and if
: DD DaysInMonth[MM] 6 is incremented by 1 and is set to DD – DaysInMonth[MM] 7 If then increment and set to 1 MM = 13 / MM > 12 8 Use of to assign value to , must have been SETDATE NewDate NewDate delared as a type DATE 9 Return date Max 7 marks
An exam paper has a maximum of 75 marks. One of five pass grades (A to E) is assigned, depending on the mark obtained. The lowest mark for a given grade is known as the grade boundary. For example, if the grade boundary for an A grade is 65 marks, then any candidate who achieves a mark of 65 or above will be awarded an A. A grade of U is awarded for marks below the E grade boundary.
The five grade boundaries are stored in a global 1D array GradeBoundary of type integer.
For example:
| Element | Value | Comment |
|---|---|---|
| GradeBoundary[1] | 65 | The minimum mark for an A grade. |
| GradeBoundary[2] | 57 | The minimum mark for a B grade. |
| GradeBoundary[3] | 43 | The minimum mark for a C grade. |
| GradeBoundary[4] | 35 | The minimum mark for a D grade. |
| GradeBoundary[5] | 27 | The minimum mark for an E grade. |
A global 2D array Result of type integer contains candidate marks for the exam. Each row relates to one candidate. Column 1 contains the candidate mark and column 2 contains the unique candidate ID.
For example, for the fourth and fifth candidates:
| Element | Mark |
|---|---|
| Result[4, 1] | 56 |
| Result[5, 1] | 54 |
| Element | ID |
|---|---|
| Result[4, 2] | 1074832 |
| Result[5, 2] | 2573839 |
There are more rows in the array than candidates who sit the exam. Any unused rows will be at the end of the array.
Candidate papers that are given a mark within two marks of any grade boundary must be checked.
For example, given the values in the example grade boundaries above, any paper that was awarded between 41 and 45 marks (inclusive) would need to be checked.
A program is being written to identify papers that need to be checked.
The programmer has defined the first program module as follows:
| Module | Description |
|---|---|
| CheckMark() | • called with a parameter of type integer representing a candidate mark • returns TRUE if the mark is within 2 of any of the five grade boundaries, otherwise returns FALSE |
(a) Write pseudocode for module CheckMark(). 6 marks
(b) A second module is defined: 8 marks
| Module | Description |
|---|---|
| CheckAll() | • called with a parameter of type integer representing the number of candidate marks in the Result array • uses CheckMark() to check each candidate mark • for each paper that needs to be checked, write the corresponding candidate ID on a separate line in a new file named GRList.txt • outputs a message with a count of how many papers need to be checked |
Write pseudocode for module CheckAll().
CheckMark() must be used to check each individual mark.
(c) The requirement changes. Instead of a new file, the module described in part (b) needs to add the corresponding candidate ID for each paper that needs to be checked to an existing file. 1 mark
Explain the change that will need to be made to CheckAll().
Show mark scheme
8(a) [6 marks]
Loop example solution FUNCTION CheckMark(Mark : INTEGER) RETURNS BOOLEAN DECLARE Index, Lower, Upper : INTEGER FOR Index 1 TO 5 Lower GradeBoundary[Index] - 2 Upper GradeBoundary[Index] + 2 IF Mark >= Lower AND Mark <= Upper THEN RETURN TRUE ENDIF NEXT Index RETURN FALSE ENDFUNCTION Mark as follows: 1 Loop through all elements in array GradeBoundary 2 Attempt to calculate range, both and , in a loop Lower Upper 3 Completely correct range calculation in a loop 4 Test if given mark / parameter, is within range in a loop 5 Set variable / immediate RETURN if recheck required in a loop 6 Return Boolean in both cases following a reasonable attempt Selection example solution FUNCTION CheckMark(Mark : INTEGER) RETURNS BOOLEAN CASE OF Mark GradeBoundary[1] – 2 TO GradeBoundary[1] + 2 : RETURN TRUE GradeBoundary[2] – 2 TO GradeBoundary[2] + 2 : RETURN TRUE GradeBoundary[3] – 2 TO GradeBoundary[3] + 2 : RETURN TRUE GradeBoundary[4] – 2 TO GradeBoundary[4] + 2 : RETURN TRUE GradeBoundary[5] – 2 TO GradeBoundary[5] + 2 : RETURN TRUE OTHERWISE : RETURN FALSE ENDCASE ENDFUNCTION Mark as follows: 1 Correct syntax used for selection structure(s) 2 Correct checks for two ranges 3 Correct checks for three ranges 4 Correct checks for four ranges 5 Correct checks for all five ranges 6 Return Boolean in both cases following a reasonable attempt
8(b) [8 marks]
Example Solution: PROCEDURE CheckAll(CNum : INTEGER) DECLARE Index, Count, ThisMark: INTEGER Count 0 OPENFILE "GRList.txt" FOR WRITE FOR Index 1 to CNum ThisMark Result[Index, 1] // 2D array: mark + ID IF CheckMark(ThisMark) = TRUE THEN WRITE "GRList.txt", NUM_TO_STR(Result[Index, 2]) Count Count + 1 ENDIF NEXT Index CLOSEFILE "GRList.txt" OUTPUT "There are ", Count, " papers to check" ENDPROCEDURE Mark as follows: 1 Procedure heading, parameter and ending. 2 Open file in write mode and subsequently close 3 Loop through all candidates CNum 4 Extract candidate mark from array in a loop Result 5 Use of with candidate mark as parameter in a loop CheckMark() 6 Test return value and if then increment in a loop TRUE Count 7 ... write ID to file ... 8 ... after conversion to a string in a loop 9 Final output of message giving number of papers to check not in a loop Max 8 marks
8(c) [1 mark]
The file will need to be opened in APPEND mode
A program is being developed to process bank card information.
When a card number is displayed, all the characters except the last four are replaced with the asterisk character '*'.
Card numbers are stored as strings. The strings are between 10 and 20 characters in length.
The function Conceal() will take a string representing a card number and return a modified string.
Example strings:
| Original string | Modified string |
|---|---|
| "1234567890" | "******7890" |
| "1234567897652" | "*********7652" |
| "1234567890123456" | "************3456" |
(a) The function Conceal() will: 6 marks
take a numeric string as a parameter representing the card number
return a string in which the asterisk character replaces all except the last four characters of the card number parameter.
Write pseudocode for the function Conceal().
Show mark scheme
2(a)
MP4 Trim asterisk string to number calculated in MP3 MP5 Extract the last four characters MP6 Concatenate trimmed asterisk string with last four characters of CardNumber MP7 Return masked string Max 6 marks DECLARE CardNumber : ARRAY [1:100, 1:2] OF STRING
2(b)(i) [2 marks]
MP1 Correct dimensions MP2 All other parts of the statement correct
2(b)(ii) [1 mark]
Any reference to BYREF // ‘by reference’
A global integer variable Tick is always incremented every millisecond (1000 times per second) regardless of the other programs running.
The value of Tick can be read by any program but the value should not be changed.
Assume that the value of Tick does not overflow.
As an example, the following pseudocode algorithm would output "Goodbye" 40 seconds after outputting "Hello".
DECLARE Start : INTEGER
OUTPUT "Hello" Start Tick
REPEAT //do nothing UNTIL Tick = Start + 40000
OUTPUT "Goodbye"
A program is needed to help a user to time an event such as boiling an egg.
The time taken for the event is known as the elapsed time.
The program contains a procedure Timer() which will:
take two integer values representing an elapsed time in minutes and seconds
use the value of variable Tick to calculate the elapsed time
output a warning message 30 seconds before the elapsed time is up
output a final message when the total time has elapsed.
For example, to set an alarm for 5 minutes and 45 seconds the program makes the following call:
CALL Timer(5, 45)
When 5 minutes and 15 seconds have elapsed, the program will output:
"30 seconds to go"
When 5 minutes and 45 seconds have elapsed, the program will output:
"The time is up!"
Write pseudocode for the procedure Timer(). 6 marks
Show mark scheme
4 [6 marks]
Example solution: PROCEDURE Timer(Mins, Secs : INTEGER) DECLARE WarningTick, EndTick : INTEGER EndTick Tick + 1000 * ((Mins * 60) + Secs) WarningTick EndTick - (30 * 1000) REPEAT //do nothing UNTIL Tick = WarningTick OUTPUT 30 seconds to go " " REPEAT //do nothing UNTIL Tick = EndTick OUTPUT The time is up! " " ENDPROCEDURE Mark as follows: MP1 Procedure heading and parameters and ending MP2 ‘ Attempt’ to calculate ‘total time’/ // ‘elapsed time’ // EndTick WarningTick MP3 Correct calculation of and EndTick WarningTick MP4 (Design mark) • Two separate loops – checking warning time then the final time, OR … • Single loop checking the final time with an IF statement to check for warning time, OR … • Single loop with two IF statements checking the warning time and final time MP5 Completely correct MP4 MP6 Output both messages (must be meaningful and follow successful MP4)
A program contains a global 1D array Data with 100 elements of type INTEGER.
The program contains a function Process() expressed in pseudocode as follows:
FUNCTION Process(Number : INTEGER, Label : STRING) RETURNS STRING DECLARE Index, Count : INTEGER DECLARE ReturnValue : STRING
Count INT(100 / Number) Index Data[Number]
CASE OF (Index MOD 2) 0 : ReturnValue TO_UPPER(RIGHT(Label, Count)) 1 : ReturnValue "****" ENDCASE
RETURN RetVal ENDFUNCTION
(a) Run-time errors can be generated in different ways. For example, a run-time error will be generated if a function is called with invalid parameters. 3 marks
The pseudocode contains three statements that could generate a run-time error.
Write the three statements and explain how each could generate a run-time error.
Statement 1
Explanation
Statement 2
Explanation
Statement 3
Explanation
(b) One type of run-time error can cause a program to stop responding (‘freezing’). 2 marks
Identify a particular type of programming construct that can generate this type of error and explain why it occurs.
Construct
Explanation
(c) The function Process() contains a selection construct using a CASE structure. 2 marks
Write pseudocode using a single selection construct with the same functionality without using a CASE structure.
Show mark scheme
5(a) [3 marks]
MP1 Count INT(100 / Number) Number could be zero (giving a divide by zero) MP2 Index Data[Number] Potential error: Value could be outside the range of array indices Number MP3 ReturnValue TO_UPPER(RIGHT(Label, Count)) Potential Error: Number to extract may be too big / negative / out of range for use in the function // has insufficient characters RIGHT Label MP4 RETURN RetVal Potential Error: There is no value to be returned // there is no variable named RetVal Mark as follows: 1 mark for each statement and description Max 3 marks
5(b) [2 marks]
MP1 Construct: A (pre/post) conditional loop MP2 Explanation: The terminating condition is never satisfied
5(c) [2 marks]
Example solution : IF Index Mod 2 = 0 THEN ReturnValue TO_UPPER(RIGHT(Label, Count)) ELSE ReturnValue
" " ENDIF Mark as follows: MP1 IF...THEN...ELSE...ENDIF MP2 Both correct assignments and the correct test/logic
A shop sells sandwiches and snacks. The owner chooses a ‘daily special’ sandwich which is displayed on a board outside the shop. Each ‘daily special’ has two different fillings and is made with one type of bread.
The owner wants a program to randomly choose the ‘daily special’ sandwich.
The program designer decides to store the possible sandwich fillings in a 1D array of type string.
The array is declared in pseudocode as follows:
DECLARE Filling : ARRAY [1:35] OF STRING
Each element contains the name of one filling.
An example of the first five elements is as follows:
| Index | Element value |
|---|---|
| 1 | "Cheese" |
| 2 | "Onion" |
| 3 | "Salmon" |
| 4 | "Anchovies" |
| 5 | "Peanut Butter" |
A second 1D array stores the possible bread used:
DECLARE Bread : ARRAY [1:10] OF STRING
Each element contains the name of one type of bread.
An example of the first three elements is as follows:
| Index | Element value |
|---|---|
| 1 | "White" |
| 2 | "Brown" |
| 3 | "Pitta" |
Both arrays may contain unused elements. The value of these will be an empty string and they may occur anywhere in each array.
A procedure Special() will output a message giving the ‘daily special’ sandwich made from two randomly selected different fillings and one randomly selected bread.
Unused array elements must not be used when creating the ‘daily special’ sandwich.
Using the above examples, the output could be:
"The daily special is Cheese and Onion on Brown bread."
(a) Complete the pseudocode for the procedure Special(). 7 marks
Assume that both arrays are global.
PROCEDURE Special()
ENDPROCEDURE
(b) The owner decides that some combinations of fillings do not go well together. For example, anchovies and peanut butter. 2 marks
Describe how the design could be changed to prevent certain combinations being selected.
Show mark scheme
6(a) [7 marks]
Example solution: PROCEDURE Special() DECLARE Index : INTEGER DECLARE Filling1, Filling2 : STRING REPEAT Index INT(RAND(35)) + 1 UNTIL Filling[Index] <> "" Filling1 Filling[Index] REPEAT Index INT(RAND(35)) + 1 UNTIL Filling[Index] <> AND Filling1 <> "" Filling[Index] Filling2 Filling[Index] REPEAT Index INT(RAND(10) + 1) UNTIL Bread[Index] <> "" OUTPUT The daily special is , Filling1, and , __ " " " " Filling2, on , Bread[Index], bread. " " " " ENDPROCEDURE Mark as follows: MP1 Loop for Filling 1, avoiding unused elements MP2 Loop for Filling 2 avoiding unused elements MP3 Check Filling 2 is different from Filling 1 – could correctly compare either the indices or the array contents MP4 Loop for Bread, avoiding unused elements MP5 Using / RAND(10) RAND(35) MP6 Completely correct use of including and +1 in all RAND()
INT() cases MP7 Correct output - once only – following a reasonable attempt at selection of filings and bread
6(b) [2 marks]
Answers include: MP1 For each filling, create a list of acceptable / incompatible fillings/indexes MP2 When selecting the second filling, (as well as checking for an unused element) check that the filling / index is / is not on the list ALTERNATIVE: MP1 Create a list of ‘good’ combinations MP2 Randomly select from this list •
(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") |
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
An algorithm will:
- prompt and input a sequence of 100 integer values, one at a time
- sum the positive integers
- output the result of the sum.
(a) Write pseudocode for the algorithm. 5 marks
Assume the value zero is neither positive nor negative.
You must declare all variables used in the algorithm.
(b) The algorithm requires the use of basic constructs. One of these is sequence. 2 marks
Identify one other basic construct required by the algorithm and describe how it is used.
Construct
Use
Show mark scheme
2(a) [5 marks]
Total 0 FOR Count 1 TO 100 OUTPUT "Input an integer value" INPUT NextNumber IF NextNumber > 0 THEN Total Total + NextNumber ENDIF NEXT Count OUTPUT Total Mark as follows: MP1 Declarations of all variables used MP2 Loop for 100 iterations MP3 Prompt and input a value in a loop and MP4 Test for value > 0 // >=1 in a loop MP5 Sum the Total in a loop MP6 Output of Total after the loop Max 5 marks
2(b) [2 marks]
MP1 Construct: Iteration / Repetition MP2 Use: To loop through all 100 inputs // To loop 100 times ALTERNATIVE: MP1 Construct: Selection MP2 Use: To test whether the value input is positive
An examination paper has a maximum of 75 marks. One of five pass grades (A to E) is assigned, depending on the mark obtained. The lowest mark for a given grade is known as the grade boundary.
A program is being written to process examination marks.
The five grade boundaries are stored in a global 1D array GB of type INTEGER, for example:
| Index | Value | Comment |
|---|---|---|
| 1 | 65 | The minimum mark for an A grade. |
| 2 | 57 | The minimum mark for a B grade. |
| 3 | 43 | The minimum mark for a C grade. |
| 4 | 35 | The minimum mark for a D grade. |
| 5 | 27 | The minimum mark for an E grade. |
Any paper that achieves a mark within 2 marks of a grade boundary must be checked. Using the given table, a paper with 45 marks would need to be checked.
(a) The pseudocode algorithm to determine whether a paper should be checked is as shown. 4 marks
The mark for the paper is stored in variable Mark. Global variables Mark, Index, Upper and Lower are declared as integers.
Complete the pseudocode.
FOR Index ← 1 TO
Lower ← GB[Index] - 2
Upper ←
IF Mark ______ AND Mark ______ THEN
OUTPUT "Check this paper"
ENDIF
NEXT Index
(b) An alternative algorithm to determine if a paper needs to be checked uses a global 1D array Check, containing 76 elements of type BOOLEAN. The indices of the array are from 0 to 75 (inclusive), corresponding to the range of possible marks.
An element value in Check is TRUE if the index is within 2 marks of a grade boundary. For example, in the case where the C grade boundary is 43 the corresponding part of the Check array would be as follows:
← The grade boundary for a C grade
| Index | Value |
|---|---|
| 40 | FALSE |
| 41 | TRUE |
| 42 | TRUE |
| 43 | TRUE |
| 44 | TRUE |
| 45 | TRUE |
| 46 | FALSE |
(i) The mark for a given paper is stored in variable Mark. 2 marks
Describe how an algorithm would use the Check array to determine whether this paper should be checked.
(ii) A procedure GBInitialise() will initialise the Check array using values from the GB array. 6 marks
Note it can be assumed that the maximum grade boundary value for A is 70 and the minimum value for E is 15.
Write pseudocode for the procedure.
Show mark scheme
4(a) [4 marks]
One mark per highlighted part: FOR Index 1 TO 5 Lower GB[Index] - 2 Upper GB[Index] + 2 // Lower + 4 IF Mark
= Lower AND Mark <= Upper THEN // IF Mark <= Upper AND Mark = Lower THEN OUTPUT "Check this paper" ENDIF NEXT Index
4(b)(i) [2 marks]
MP1 Use as the index to the array // to specify an array Mark Check element MP2 If value of indexed element is then the paper will need to be TRUE, checked
4(b)(ii)
ALTERNATIVE – Example using selection Version 2 DECLARE ThisIndex, GBIndex : INTEGER DECLARE Lower, Higher : INTEGER FOR ThisIndex 0 TO 75 For GBIndex 1 T0 5 Lower GB[GBIndex] - 2 Higher GB[GBIndex] + 2 IF ThisIndex >= Lower AND ThisIndex <= Higher THEN Check[ThisIndex] TRUE ELSE Check[ThisIndex] FALSE ENDIF NEXT Index NEXT ThisIndex Mark as follows: MP1 Procedure heading and ending MP2 Loop through array// loop from 0 to 75 Check MP3 Attempt at using CASE / Selection structure with five clauses/ f ive checks for range MP4 Extract GB grade MP5 Compare with each element in GB array 2 ThisIndex MP6 Assign each element of array to if in range or if Check TRUE FALSE not in range
In some countries, on the third Sunday in March, daylight saving time begins when clocks move forward by one hour.
A module AdjustClock() will take an integer parameter representing a year. The module will return an integer value representing the number of the day in March on which the clocks move forward.
For example, the following line of pseudocode would assign DayNumber the value 20:
DayNumber AdjustClock(2022)
←
Write pseudocode for the function AdjustClock().
Date functions from the insert should be used in your solution. 7 marks
Show mark scheme
6 Mark as follows:
MP1 Function heading, parameter, ending and return type MP2 Declare local integer variable that is used to hold a day number MP4 Attempt to use both and SETDATE() DAYINDEX() MP5 Correctly generate value of type using for first of DATE SETDATE() March / specific day in March MP6 Test if date represents a Sunday / specific day using DAYINDEX() and calculate third Sunday // Correctly calculate third Sunday for a value returned by for one day DAYINDEX() MP7 Calculate third Sunday for other six days MP8 Return day number of third Sunday Max 7 marks
An algorithm has three steps. It will:
repeatedly input a pair of numeric values
AandBcount the number of pairs that are input until
Ahas been greater thanB10 timesoutput the number of pairs that were input.
(a) Complete the program flowchart. 5 marks

Show mark scheme
2(a) [2 marks]
One mark per outlined region: 1 Initialise both counts 2 Increment every time a pair is input Tries 3 Compare A > B and increment if TRUE Count 4 Test for Count = 10 (10 time A > B) – MUST include Yes / No labels th 5 If so output , otherwise loop Tries
2(b) [3 marks]
One mark per point: 1 A (variable of type) string will be input // by example e.g. “67,72” 2 A special / identified character would need to be used to separate each numeric value // all numbers are fixed length
(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] 0NEXT Index |
|||
WRITEFILE ThisFile, "****" |
|||
UNTIL Level > 25 |
|||
IF Mark > 74 THEN READFILE OldFile, DataENDIF |
(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.

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
A program is being developed.
(a) An algorithm for part of the program will:
input three numeric values and assign them to identifiers
Num1,Num2andNum3assign the largest value to variable
Ansoutput a message giving the largest value and the average of the three numeric values.
Assume the values are all different and are input in no particular order.
Complete the program flowchart on page 5 to represent the algorithm.
Show mark scheme
2(a) [5 marks]
Mark points 1 Condition for selecting one of the input numbers as largest value 2 … and assign to Ans 3 Condition for selecting largest number for all three number input and assigning to Ans 4 Average calculated using , and and stored in a variable. Num1 Num2 Num3 Reject use of DIV 5 Output of and average in output symbol / parallelogram Ans
2(b) [4 marks]
Example solutions: Flag GetStat() WHILE Flag <> TRUE FOR Port 1 TO 3 CALL Reset(Port) NEXT Port Flag GetStat() ENDWHILE Alternative: REPEAT Flag GetStat() IF Flag <> TRUE THEN FOR Port 1 TO 3 CALL Reset(Port) NEXT Port ENDIF UNTIL Flag = TRUE One mark per point: 1 (Outer) conditional loop testing Flag 2 Correct assignment of from in a loop Flag GetStat() 3 (Inner) loop checking / counting port // Check if is different to 4 Port 4 … loop for 3 iterations 5 a call to in a loop Reset()
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
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:
- Procedure heading and ending and declaration of all variables used
- 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
A procedure TwoParts() will input a sequence of real values, one at a time.
The procedure will:
process the sequence in two parts
form a first total by adding the values until the first zero
form a second total by adding the values after the first zero until the second zero
output the average of the two totals, together with a suitable message.
Values input in the first part are totalled using global variable TotalA and those input in the second part are totalled using global variable TotalB.
(a) Write pseudocode for the procedure TwoParts(). 6 marks
(b) The value zero denotes the split between the two parts of the sequence.
The requirement changes and now there may be up to 20 parts.
(i) Identify a suitable data structure that could be used to store the different total values. 2 marks
(ii) Describe three benefits of using the data structure given in part (b)(i) . 3 marks
1
2
3
Show mark scheme
4(a) [2 marks]
Example solution: PROCEDURE TwoParts() DECLARE NextNum, Average : REAL TotalA 0.0 // 0 TotalB 0.0 // 0 REPEAT INPUT NextNum TotalA TotalA + NextNum UNTIL NextNum = 0 REPEAT INPUT NextNum TotalB TotalB + NextNum UNTIL NextNum = 0 Average (TotalA + TotalB) / 2 OUTPUT "The average is ", Average ENDPROCEDURE Mark as follows:
- Procedure heading and ending
- Declare all local variables
- Initialise and TotalA TotalB
- First conditional loop until zero entered, summing // Loop until TotalA both parts (sequences) have been entered
- Second conditional loop until zero entered, summing // Loop TotalB summing appropriate Totals
- Calculation of average and output with a message // Calculation of the average for the values making up the two totals and both output with a suitable message
4(b)(i) [3 marks]
(1D) array of 20 reals Marks as follows: 1 mark for array 1 mark for 20 reals
4(b)(ii)
One mark per point: 1 (Multiple instances referenced via a single identifier so) fewer identifiers needed 2 Easier to process / search / organise / access the data // Values may be accessed via a loop-controlled variable /an index //An array / data can be iterated through 3 Makes the program/algorithm easier to write / design / understand / maintain / modify // Simplifies the program // Easier to debug / test
A program is being designed in pseudocode.
The program contains the following declaration:
DECLARE Data : ARRAY[1:1000] OF STRING
A procedure ArrayInitialise() is written to initialise the values in the array:
PROCEDURE ArrayInitialise(Label : STRING) DECLARE Index : INTEGER Index 1 WHILE Index <= 1000 CASE OF (Index MOD 2) 0 : Data[Index] FormatA(Label) Index Index + 1 1 : Data[Index] FormatB(Label) Index Index + 1 ENDCASE ENDWHILE ENDPROCEDURE
Functions FormatA() and FormatB() apply fixed format case changes to the parameter string.
(a) The design of the procedure does not use the most appropriate loop construct. 2 marks
Suggest a more appropriate construct that could be used and explain your choice.
Construct
Explanation
(b) The algorithm calls one of the functions FormatA() and FormatB() each time within the loop. 4 marks
Explain why this is not efficient and suggest a more efficient solution.
Show mark scheme
5(a) [4 marks]
One mark per point Count-controlled loop the number of iterations is known
5(b) [6 marks]
Two mark for Statement of Problem: 1 The functions will return the same value every time they are called 2 ... because / the parameter value does not change within the loop Label Two marks for Solution: 3 Assign and to two (local) variables FormatA(Label) FormatB(Label) before the loop 4 Use the (new) variables in place of the function calls / in the loop // Replace the references to and in the FormatA() FormatB() CASE clauses with the new variable names
A global array is declared in pseudocode as follows:
DECLARE Data : ARRAY[1:150] OF STRING
A function TooMany() will:
- take two parameters:
a string (the search string)
an integer (the maximum value)
- count the number of strings in the array that exactly match the search string
- return
TRUEif the count is greater than the maximum value, otherwise will returnFALSE
(a) Write pseudocode for the function TooMany(). 6 marks
Show mark scheme
4(a) [6 marks]
BOOLEAN DECLARE Count, Index : INTEGER Count 0 FOR Index 1 TO 150 IF Data[Index] = Search THEN Count Count + 1 ENDIF NEXT Index IF Count > Max THEN RETURN TRUE ELSE RETURN FALSE ENDIF ENDFUNCTION MP1 Function heading, ending and return type MP2 Declare Count and Index as integers MP3 Initialise Count MP4 Loop (any type) for 150 iterations MP5 Compare Data element with parameter - if equal, increment Count in a loop MP6 Compare Count with Max and return Boolean in both cases outside the loop
4(b) [3 marks]
MP1 Test for row being even number MP2 Test for either column value equal to Search IF Row MOD 2 = 0 AND __ (Data[Row, 1] = Search OR Data[Row, 2] = Search) THEN ALTERNATIVE using nested : IFs IF Row MOD 2 = 0 THEN IF Data[Row, 1] = Search OR Data[Row, 2] = Search THEN MP3 Selection structure is either: • Single IF statement using AND, or • Two nested IFs using AND, or • Single IF and the use of a two-iteration loop Either of these structures correctly formed scores the mark ALTERNATIVE SOLUTION: A FOR loop using ‘STEP 2’ FOR Row 2 TO 150 / NEXT Row STEP 2 Data[Row, 1] = Search OR Data[Row, 2] = Search) THEN MP1 should be
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:
- The Boolean parameter value is
TRUE - 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:
MyStringis initialised to an empty string beforeMyOutput()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.
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
A class of students are developing a program to send data between computers. Many computers are connected together to form a wired network. Serial ports are used to connect one computer to another.
Each computer:
is assigned a unique three-digit ID
has three ports, each identified by an integer value
is connected to between one and three other computers.
Messages are sent between computers as a string of characters organised into fields as shown:
<STX><DestinationID><SourceID><Data><ETX>
|Field<br>number|Field name|Description|
|---|---|---|
|n/a|`STX`|a single character marking the start of the message<br>(ASCII value 02)|
|1|`DestinationID`|three numeric characters that identify the destination computer|
|2|`SourceID`|three numeric characters that identify the source computer|
|3|`Data`|a variable length string containing the data being sent<br>(Minimum length is 1 character)|
|n/a|`ETX`|a single character marking the end of the message<br>(ASCII value 03)|
For example, the following message contains the data "Hello Kevin" being sent from computer "101" to computer "232":
<STX>"232101Hello Kevin"<ETX>
Each computer will run a copy of the same program. Each program will contain a global variable,
MyID of type string, that contains the unique ID of the computer in which the program is running.
The programmer has defined the first two program modules as follows:
| Module | Description |
|---|---|
Transmit()(already written) |
• takes two parameters:o a string containing a messageo an integer containing a port number• transmits the message using the given port |
SendFile() |
• takes three parameters:o a string containing a text file nameo a string containing a Destination IDo an integer containing a Port number• transmits the file one line at a time • transmits a final message with data string " ****" |
(a) Write pseudocode for module SendFile() . 7 marks
Assume:
module
Transmit()has already been written and is used to transmit a messagethe value of
MyIDmay be used asSourceIDthe file specified contains no blank lines
the file specified does not contain the line "
****"
(b) Module SendFile() is used to copy a file from one computer to another. 2 marks
A module within the program running on the destination computer will receive the data and write it to a new file.
Explain why module SendFile() transmits the message with data string "****" after the
last line of the file.
(c) One of the text files to be sent contains several blank lines (lines that do not contain any text).
(i) Explain why this is a problem. 2 marks
(ii) Explain how the message format could be changed to allow a blank line to be sent. 2 marks 6 marks
Question 8(d) starts on page 18.
| (d) A new module has b | been defined: |
|---|---|
| Module | Description |
GetField() |
• takes two parameters:o a string containing a messageo an integer containing a field number• If the field number is valid (in the range 1 to 3, inclusive), it returns a string containing the required field, otherwise it returns an empty string. |
As a reminder, a message is defined as follows:
<STX><DestinationID><SourceID><Data><ETX>
|Field<br>number|Field name|Description|
|---|---|---|
|Not applicable|`STX`|a single character marking the start of the message<br>(ASCII value 02)|
|1|`DestinationID`|three numeric characters that identify the destination computer|
|2|`SourceID`|three numeric characters that identify the source computer|
|3|`Data`|a variable length string containing the data being sent<br>(Minimum length is 1 character)|
|Not applicable|`ETX`|a single character marking the end of the message<br>(ASCII value 03)|
Write pseudocode for module GetField() .
Show mark scheme
8(a) [7 marks]
INTEGER) DECLARE FileData : STRING CONSTANT STX = CHR(02) CONSTANT ETX = CHR(03) OPENFILE FileName FOR READ WHILE NOT EOF(FileName) READFILE FileName, FileData FileData STX & DestID & MyID & FileData & ETX CALL Transmit(FileData, Port) ENDWHILE CLOSEFILE FileName CALL Transmit(STX & DestID & MyID & "" & ETX, Port) ENDPROCEDURE Mark as follows: MP1 OPEN file in READ mode – using parameter - and subsequently CLOSE MP2 Conditional loop to EOF() MP3 Use of to get a line from the file READFILE MP4 ‘Attempt’ to form a message (minimum is ) DestID, MyID, FileData MP5 Message formed is completely correct MP6 Call with correct MP4 string in a loop Transmit() MP7 Transmit the "" message (all parts present) after the loop
8(b) [2 marks]
Max 2 marks MP1 Indicates that all the lines of the file have been sent // it is the end of the transmission / file transfer MP2 So that the receiving program can stop waiting for further data MP3 The file can be closed / saved
8(c)(i) [2 marks]
MP1 A message cannot contain a zero-length data field MP2 … so a blank line cannot be sent // there is no way to send a blank line
8(c)(ii) [2 marks]
MP1 Append a (special) character to the start of the message text MP2 interpret the new field data as a blank line ALTERNATIVE MP1 Change the message protocol and use an additional field to act as an indicator MP2 Interpret the new field data FUNCTION GetField(Msg : STRING, FieldNo : INTEGER)
8(d) [6 marks]
RETURNS STRING DECLARE RetString : STRING CASE OF FieldNo 1 : RetString MID(Msg, 2, 3) 2 : RetString MID(Msg, 5, 3) 3 : RetString MID(Msg, 8, LENGTH(Msg) - 8) OTHERWISE : RetString "" ENDCASE RETURN RetString ENDFUNCTION MP1 Use of or CASE ... ENDCASE IF ... THEN ... ENDIF MP2 Field 1 and Field 2 extracted correctly MP3 Calculate a length of field 3 MP4 Field 3 extracted correctly MP5 Return empty string in case of invalid parameter (via or OTHERWISE initialisation) MP6 Final , after a reasonable attempt RETURN
A procedure Count() will:
- input a value (all values will be positive integers)
- count the number of odd values and count the number of even values
- repeat from step 1 until the value input is 99
- output the two count values, with a suitable message.
The value 99 must not be counted.
(a) Write pseudocode for the procedure Count() . 6 marks
(b) The procedure Count() is to be tested. 3 marks
Typical test data would consist of odd and even values, for example:
23, 5, 64, 100, 2002, 1, 8, 900, 99
The purpose of this test would be to test a typical mix of even and odd values and check the totals.
Give three test data sequences that may be used to test different aspects of the procedure.
Do not include invalid data.
Sequence 1:
Test data
Purpose of test.
Sequence 2:
Test data
Purpose of test.
Sequence 3:
Test data
Purpose of test.
Show mark scheme
4(a) [6 marks]
Example Solution PROCEDURE Count() DECLARE COdd, CEven, ThisNum : INTEGER COdd 0 CEven 0 INPUT ThisNum WHILE ThisNum <> 99 IF ThisNum MOD 2 = 1 THEN COdd COdd + 1 ELSE CEven CEven + 1 ENDIF INPUT ThisNum ENDWHILE OUTPUT "Count of odd and even numbers: ", COdd, CEven ENDPROCEDURE Mark as follows Max 6 marks: 1 Procedure heading and ending 2 Local , and declared as integers COdd CEven ThisNum 3 Conditional loop while ThisNum <> 99 4 Input in a loop ThisNum 5 Check is odd or even in a loop ThisNum 6 Increment appropriate count in a loop , both counts must have been initialised before loop 7 After the loop output and with a suitable message following COdd CEven a reasonable attempt at counting
4(b) [3 marks]
One mark per set, including stated purpose. Max 3 marks Example answers: 1 data set with (only) odd values, terminated with 99 2 data set with (only) even values, terminated with 99 3 data sets with same number of odd and even values, terminated with 99 4 data sets with all even / all odd with just one odd/even value, terminated with 99 5 data sets with no values just final 99 6 data sets without (terminating) 99 // missing or incorrectly placed 99
A class of students are developing a program to send data between computers. Many computers are connected together to form a wired network. Serial ports are used to connect one computer to another.
Each computer:
is assigned a unique three-digit ID
has three ports, each identified by an integer value
is connected to between one and three other computers.
Data is sent as individual message strings. Each string contains the destination ID (the ID of the computer that is to receive the message) followed by the data:
<DestinationID><Data>
Messages may pass through several computers on the way to their destination. When a message arrives at a computer, that is not the destination, the program needs to forward it on to another computer using one of its serial ports.
The port to use is obtained from information that is stored in an array RouteTable .
RouteTable is a global 2D array of integers. It is declared in pseudocode as follows:
DECLARE RouteTable : ARRAY[1:6,1:3] OF INTEGER
The values in the first two columns of RouteTable define a range of ID values.
Column 3 gives the corresponding port number to use when forwarding the message to a computer
with an ID within this range.
For example, the contents of RouteTable could be:
| Column 1 | Column 2 | Column 3 |
|---|---|---|
100 |
199 |
1 |
200 |
259 |
2 |
| −1 | <undefined> |
<undefined> |
260 |
399 |
2 |
400 |
599 |
3 |
600 |
999 |
1 |
In this example, a message that arrives with a DestinationID of "283" will be forwarded using
port 2.
Row 3 in the example shows an unused row. These may occur anywhere. Unused rows have the column 1 element set to −1. The value of unused elements in the other two columns is undefined.
The programmer has defined the first program module as follows:
| Module | Description |
|---|---|
GetPort() |
• takes a DestinationID as a parameter of type string• searches for the range corresponding to the DestinationID in the array • returns the port number, or returns −1 if no corresponding range is found |
(a) Write pseudocode for module GetPort() . 7 marks
Assume DestinationID contains a valid three-digit string.
(b) Copies of the same program will run on each computer. The program contains a global variable MyID of type string, which contains the unique ID of the computer in which the program is running. 7 marks
When messages are received, they are placed on one of two stacks. Stack 1 is used for messages that have reached their destination and stack 2 is used for messages that will be forwarded on to another computer.
Additional modules are defined:
| Module | Description |
|---|---|
StackMsg()(already written) |
• takes two parameters: ○ a string representing a message ○ an integer representing the stack number • adds the message to the required stack • returns TRUE if the message is added to the required stack,otherwise returns FALSE |
ProcessMsg() |
• takes a message as a parameter of type string • ignores any message with a zero-length data field • extract the DestinationID from the message• checks whether the DestinationID is this computer orwhether the message is to be forwarded • uses StackMsg() to add the message to the appropriatestack • outputs an error if the message could not be added to the stack |
Write pseudocode for module ProcessMsg() .
Module StackMsg() must be used.
(c) The program contains a module GetFile() which receives text files sent from another computer.
Lines from the file are sent one at a time. Each message contains one line and ProcessMsg()
from part (b) adds each message as it is received onto stack 1.
Module GetFile() removes messages from stack 1 and writes the data to a text file.
There is a problem. Under certain circumstances, the received file does not appear as expected.
Assume that while a file is being received ProcessMsg() receives only messages containing
lines from the file.
(i) Describe the circumstances and explain the problem. 3 marks
Circumstances
Explanation
(ii) Suggest a more appropriate Abstract Data Type that could be used to store the messages that would not have the same problem. 1 mark
Show mark scheme
8(a)
Port RouteTable[1, 3] END IF IF RouteTable[2, 1] <> -1 AND RouteTable[2, 1] >= DNum AND __ RouteTable[2, 2] <= DNum THEN Port RouteTable[2, 3] END IF IF RouteTable[3, 1] <> -1 AND RouteTable[3, 1] >= DNum AND __ RouteTable[3, 2] <= DNum THEN Port RouteTable[3, 3] END IF IF RouteTable[4, 1] <> -1 AND RouteTable[4, 1] >= DNum AND __ RouteTable[4, 2] <= DNum THEN Port RouteTable[4, 3] END IF IF RouteTable[5, 1] <> -1 AND RouteTable[5, 1] >= DNum AND __ RouteTable[5, 2] <= DNum THEN Port RouteTable[5, 3] END IF IF RouteTable[6, 1] <> -1 AND RouteTable[6, 1] >= DNum AND __ RouteTable[6, 2] <= DNum THEN Port RouteTable[6, 3] END IF RETURN Port ENDFUNCTION Mark as follows Max 7 : 1 Function heading and ending including parameter and return type 2 Convert parameter to a number 3 Skip all unused elements 4 Attempt to check one range 5 Check two ranges with destination correctly 6 Check all ranges with destination correctly 7 Store port value if destination matched 8 Return port value including -1 if no match found
8(b) [7 marks]
Example solution PROCEDURE ProcessMsg(ThisMsg : STRING) DECLARE ThisDest : STRING DECLARE Response : BOOLEAN DECLARE StackNum : INTEGER IF LENGTH(ThisMsg) >= 4 THEN ThisDest LEFT(ThisMsg, 3) IF ThisDest = MyID THEN // It's for this computer StackNum 1 ELSE StackNum 2 ENDIF Response StackMsg(ThisMsg, StackNum) IF Response = FALSE THEN OUTPUT "Message discarded - no room on stack" ENDIF ENDIF ENDPROCEDURE Mark as follows:
- Ignore message if data field is empty
- Extract from ThisDest ThisMsg
- Test if destination is this computer
- Attempt to use StackMsg()
Fully correct use of for both cases / stacks StackMsg() 6. Test return value for both cases StackMsg() 7. Following a reasonable attempt at MP6 output warning if StackMsg() returns FALSE
8(c)(i) [3 marks]
One mark per point Max 3 marks: Decide on scenario and mark accordingly. Scenario one : • If more than one line is / all lines are stored on the stack (before line(s) are removed) • The stack operates as a FILO device // Last item added to stack will be in first item out • So lines in the file appear out of sequence Scenario two: • Stack is Full • Not all lines can be stored on the stack • so resulting file will not contain all the original lines Scenario three: • (All) the data in a line read can’t be stored on the stack • Stack elements have not been allocated enough memory • so only part of each line is stored in the file Scenario four: • Stack is empty • The stack is being read faster than it is being written to • so blank lines may be inserted into the file
8(c)(ii) [1 mark]
Queue
A procedure RandList() will output a sequence of 25 random integers, where each integer is
larger than the previous one.
(a) Write pseudocode for procedure RandList() . 6 marks
(b) Procedure RandList() is modified so that the random numbers are also written into a 1D array Result . 1 mark
A new module is written to confirm that the numbers in the array are in ascending order.
This module contains an IF statement that performs a comparison between elements:
IF (Result[x + 1] = Result[x]) OR (Result[x] > Result[x + 1]) THEN
Sequence FALSE
# ←
ENDIF
Write a simplified version of the conditional clause.
Show mark scheme
4(a) [6 marks]
DECLARE Count, BaseNum, ThisNum : INTEGER CONSTANT StepVal = 10 BaseNum 0 FOR Count 1 TO 25 ThisNum BaseNum + INT(RAND(StepVal)) OUTPUT ThisNum BaseNum BaseNum + StepVal NEXT Count ENDPROCEDURE MP1 Procedure heading and ending MP2 Local loop counter as integer Count MP3 Loop to iterate 25 times or more for each unique number MP4 ‘Attempt’ to generate a random number including use of in a INT() loop MP5 Ensure that number generated is greater than previous and change ‘previous’ MP6 Output random number after an attempt at MP5 in a loop
4(b) [1 mark]
One mark for simplified logical expression: MP1 Result[x + 1] <= Result[x] ALTERNATIVE SOLUTION: Result[x] >= Result[x + 1]
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
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
A class of students are developing a program to send data between computers. Many computers are connected together to form a wired network. Serial ports are used to connect one computer to another.
Each computer:
is assigned a unique three-digit ID
has three ports, each identified by an integer value
is connected to between one and three other computers.
Messages are sent between computers as a string of characters organised into fields as shown:
<STX><DestinationID><SourceID><Data><ETX>
|Field name|Description|
|---|---|
|`STX`|a single character marking the start of the message<br>(ASCII value 02)|
|`DestinationID`|three numeric characters identifying the destination computer|
|`SourceID`|three numeric characters identifying the source computer|
|`Data`|a variable length string containing the data being sent<br>(Minimum length is 1 character)|
|`ETX`|a single character marking the end of the message<br>(ASCII value 03)|
For example, the following message contains the data "Hello Jack" being sent from computer "202" to computer "454":
<STX>"454202Hello Jack"<ETX>
Each computer will run a copy of the same program. Each program will contain a global variable
MyID of type string which contains the unique ID of the computer in which the program is running.
The first two program modules are defined as follows:
| Module | Description |
|---|---|
GetData()(already written) |
• returns the data field from a message that has been received • If no message is available, the module waits until one has been received. |
ReceiveFile() |
• takes a file name as a parameter of type string • creates a text file with the given file name (no checking required) • writes the data field returned by GetData() to the file• repeats until the data field is "****", which is not written to the file • outputs a final message giving the total number of characters written to the file, for example: 132456 characters were written to newfile.txt |
(a) Write pseudocode for module ReceiveFile() . 7 marks
Module GetData() has already been written and must be used.
(b) The use of the string "****" as explained in the module description for ReceiveFile() may cause a problem. 3 marks 7 marks
Explain the problem and suggest a solution.
Problem
Solution
| c) Two new modules | s are defined, which will allow two users to exchange messages. |
|---|---|
| Module | Description |
Transmit()(already written) |
• takes two parameters: ○ a string representing a message ○ an integer representing a port number • transmits the message using the given port |
Chat() |
• takes two parameters: ○ a string representing a Destination ID ○ an integer representing a port number • extracts data from a received message using GetData() andoutputs it • forms a message using data input by the user and sends it using Transmit()• repeats until either the output string or the sent string is "Bye" |
Reminders:
Each program contains a global variable
MyIDof type string which contains the unique ID of the computer in which the program is running.Messages are sent between computers as a string of characters organised into fields as shown:
<STX><DestinationID><SourceID><Data><ETX>
Write pseudocode for module Chat().
Modules GetData() and Transmit() must be used.
(d) Module GetData() returns the data field from a message that has been received. If no message is available, the module waits until one has been received. 3 marks
Explain the limitation of this on module Chat() from part (c) .
Describe a modification to GetData() to address this limitation.
Limitation
Modification
Show mark scheme
8(a) [7 marks]
DECLARE FileData : STRING DECLARE CharCount : INTEGER CONSTANT Terminator = "****" OPENFILE FileName FOR WRITE FileData GetData() CharCount 0 WHILE FileData <> Terminator WRITEFILE FileName, FileData CharCount CharCount + LENGTH(FileData) FileData GetData() ENDWHILE CLOSEFILE FileName OUTPUT CharCount (, " characters were written to ", FileName) ENDPROCEDURE MP1 OPEN file in WRITE mode and subsequently CLOSE MP2 Conditional loop until terminator received MP3 ‘Attempted’ use of – Ignore CALL … GetData() MP4 Fully correct use to return the data in a loop GetData() MP5 Maintain in a loop CharCount MP6 Write each line to the file - except the terminator in a loop MP7 Final output of message giving number of characters written outside loop
8(b) [3 marks]
Max 3 marks Problem: • If the file being sent contains a line of the string "****" • then the file being written by will end at this point // ReceiveFile() subsequent file lines will be lost Solution: • Read the file (at the sending end) to find the number of lines it contains • Send an initial message which defines the number of lines in the file ALTERNATIVE SOLUTION: • (Transmitter program) chooses a different terminator string / character that doesn't occur in the file • Transmitter program sends the terminator string / character before first line of file / before the transfer begins PROCEDURE Chat(Destination : STRING, Port : INTEGER)
8(c) [7 marks]
DECLARE Data : STRING DECLARE Finished : BOOLEAN CONSTANT Terminator = "Bye" CONSTANT STX = CHR(2) CONSTANT ETX = CHR(3) Finished FALSE REPEAT Data GetData() OUTPUT Data IF Data = Terminator THEN Finished TRUE ENDIF IF NOT Finished THEN //about to reply INPUT Data Transmit(STX & Destination & MyID & Data & ETX, Port) IF Data = Terminator THEN Finished TRUE ENDIF ENDIF UNTIL Finished = TRUE ENDPROCEDURE Conditional loop MP1 Conditional loop MP2 Test for terminator in both cases MP3 Use to get the data from the message GetData() MP4 the data in a loop OUTPUT MP5 the data reply INPUT MP6 ‘Attempted ‘ use of to send it in a loop Transmit MP7 Correct formation of parameters to Transmit()
8(d) [3 marks]
Note: Max 3 marks (from either limitation or modification list) Limitation: 1 does not return a value until a message has been received GetData() 2 So once a message has been sent the user has to wait for a reply // chat is half-duplex Modification: 3 If no response allow the receiver to exit chat at any time … 4 should immediately return a suitable message // set a time GetData() limit 5 ... which can detect and respond by allowing the conversation to Chat() continue
This iterative pseudocode algorithm for the function IterativeVowels() takes a string as a
parameter and counts the number of lower-case vowels in this string.
The vowels are the letters a, e, i, o and u.
FUNCTION IterativeVowels(Value : STRING) RETURNS INTEGER
DECLARE Total : INTEGER
DECLARE LengthString : INTEGER
DECLARE FirstCharacter : CHAR
Total 0
# ←
LengthString LENGTH(Value)
# ←
FOR X 0 TO LengthString - 1
# ←
FirstCharacter MID(Value, 0, 1)
# ←
IF FirstCharacter = 'a' OR FirstCharacter = 'e' OR
FirstCharacter = 'i' OR FirstCharacter = 'o' OR
FirstCharacter = 'u' THEN
Total Total + 1
# ←
ENDIF
Value MID(Value, 1, LENGTH(Value)-1)
# ←
NEXT X
RETURN Total
ENDFUNCTION
The pseudocode function MID(X, Y, Z) returns Z number of characters from string X, starting
at the character in position Y . The first character in a string is in position 0, for example:
MID("computer", 0, 3) returns "com"
The pseudocode function LENGTH(X) returns the number of characters in the string X, for
example:
LENGTH("computer") returns 8
Show mark scheme
1(a)(i) [5 marks]
One mark each to max 5 • Function header (and end where appropriate) taking one string parameter • Calculating length of parameter string • Looping correct number of times • Checking the first character against all vowels • Accessing the remainder of the string • Remainder of function correct with nothing extra i.e. totalling, must match structure of given algorithm
FirstCharacter = Value.charAt(0); if(FirstCharacter == 'a' || FirstCharacter == 'e' || FirstCharacter =='i' || FirstCharacter == 'o' Total++; } Value = Value.substring(1, Value.length()); FirstCharacter = Left(Value, 1) If FirstCharacter = "a" Or FirstCharacter = "e" Or FirstCharacter = "i" Or FirstCharacter = "o" Or Total = Total + 1 End If Value = Right(Value, Len(Value) - 1)
FirstCharacter = Value[0] if FirstCharacter == 'a' or FirstCharacter == 'e' or FirstCharacter == 'i' or FirstCharacter == 'o' Total = Total + 1 Value = Value[1:len(Value)]
1(a)(ii) [2 marks]
One mark each • Calling the function with "house" • Outputting the return value Example program code: Java System.out.println(IterativeVowels("house")); VB.NET Console.WriteLine(IterativeVowels("house")) Python print(IterativeVowels("house"))
1(a)(iii) [1 mark]
One mark for screenshot outputting 3
1(b)(i) [6 marks]
One mark each • Recursive call • Function header (and end where appropriate) taking string parameter (returning integer where given) • Base case checking (length is 0) and returning 0 • Extracting first character and checking if a vowel … • … if it is a vowel, returning 1 + recursive call with 1 less character • … if not a vowel, return recursive call with 1 less character
return 0; FirstCharacter = Value.charAt(0); if(FirstCharacter == 'a' || FirstCharacter == 'e' || FirstCharacter =='i' || FirstCharacter == 'o' return 1 + RecursiveVowels(Value.substring(1, Value.length())); }else{ return RecursiveVowels(Value.substring(1, Value.length())); } Return 0 firstCharacter = Left(Value, 1) If firstCharacter = "a" Or firstCharacter = "e" Or firstCharacter = "i" Or firstCharacter = "o" Or Return 1 + RecursiveVowels(Right(Value, Len(Value) - 1)) Else Return RecursiveVowels(Right(Value, Len(Value) - 1))
End If return 0 FirstCharacter = Value[0] return 1 + RecursiveVowels(Value[1:len(Value)]) return RecursiveVowels(Value[1:len(Value)])
1(b)(ii) [1 mark]
One mark for calling recursive function with and outputting return value "imagine" Example program code: Java System.out.println(RecursiveVowels("imagine")); VB.NET Console.WriteLine(RecursiveVowels("imagine")) Python print(RecursiveVowels("imagine"))
1(b)(iii) [1 mark]
One mark for screenshot showing 4
This iterative pseudocode algorithm for the function IterativeVowels() takes a string as a
parameter and counts the number of lower-case vowels in this string.
The vowels are the letters a, e, i, o and u.
FUNCTION IterativeVowels(Value : STRING) RETURNS INTEGER
DECLARE Total : INTEGER
DECLARE LengthString : INTEGER
DECLARE FirstCharacter : CHAR
Total 0
# ←
LengthString LENGTH(Value)
# ←
FOR X 0 TO LengthString - 1
# ←
FirstCharacter MID(Value, 0, 1)
# ←
IF FirstCharacter = 'a' OR FirstCharacter = 'e' OR
FirstCharacter = 'i' OR FirstCharacter = 'o' OR
FirstCharacter = 'u' THEN
Total Total + 1
# ←
ENDIF
Value MID(Value, 1, LENGTH(Value)-1)
# ←
NEXT X
RETURN Total
ENDFUNCTION
The pseudocode function MID(X, Y, Z) returns Z number of characters from string X, starting
at the character in position Y . The first character in a string is in position 0, for example:
MID("computer", 0, 3) returns "com"
The pseudocode function LENGTH(X) returns the number of characters in the string X, for
example:
LENGTH("computer") returns 8
Show mark scheme
1(a)(i) [5 marks]
One mark each to max 5 • Function header (and end where appropriate) taking one string parameter • Calculating length of parameter string • Looping correct number of times • Checking the first character against all vowels • Accessing the remainder of the string • Remainder of function correct with nothing extra i.e. totalling, must match structure of given algorithm
FirstCharacter = Value.charAt(0); if(FirstCharacter == 'a' || FirstCharacter == 'e' || FirstCharacter =='i' || FirstCharacter == 'o' Total++; } Value = Value.substring(1, Value.length()); FirstCharacter = Left(Value, 1) If FirstCharacter = "a" Or FirstCharacter = "e" Or FirstCharacter = "i" Or FirstCharacter = "o" Or Total = Total + 1 End If Value = Right(Value, Len(Value) - 1)
FirstCharacter = Value[0] if FirstCharacter == 'a' or FirstCharacter == 'e' or FirstCharacter == 'i' or FirstCharacter == 'o' Total = Total + 1 Value = Value[1:len(Value)]
1(a)(ii) [2 marks]
One mark each • Calling the function with "house" • Outputting the return value Example program code: Java System.out.println(IterativeVowels("house")); VB.NET Console.WriteLine(IterativeVowels("house")) Python print(IterativeVowels("house"))
1(a)(iii) [1 mark]
One mark for screenshot outputting 3
1(b)(i) [6 marks]
One mark each • Recursive call • Function header (and end where appropriate) taking string parameter (returning integer where given) • Base case checking (length is 0) and returning 0 • Extracting first character and checking if a vowel … • … if it is a vowel, returning 1 + recursive call with 1 less character • … if not a vowel, return recursive call with 1 less character
return 0; FirstCharacter = Value.charAt(0); if(FirstCharacter == 'a' || FirstCharacter == 'e' || FirstCharacter =='i' || FirstCharacter == 'o' return 1 + RecursiveVowels(Value.substring(1, Value.length())); }else{ return RecursiveVowels(Value.substring(1, Value.length())); } Return 0 firstCharacter = Left(Value, 1) If firstCharacter = "a" Or firstCharacter = "e" Or firstCharacter = "i" Or firstCharacter = "o" Or Return 1 + RecursiveVowels(Right(Value, Len(Value) - 1)) Else Return RecursiveVowels(Right(Value, Len(Value) - 1))
End If return 0 FirstCharacter = Value[0] return 1 + RecursiveVowels(Value[1:len(Value)]) return RecursiveVowels(Value[1:len(Value)])
1(b)(ii) [1 mark]
One mark for calling recursive function with and outputting return value "imagine" Example program code: Java System.out.println(RecursiveVowels("imagine")); VB.NET Console.WriteLine(RecursiveVowels("imagine")) Python print(RecursiveVowels("imagine"))
1(b)(iii) [1 mark]
One mark for screenshot showing 4
Function Replace() will:
- take three parameters:
a string (the original string)
a char (the original character)
a char (the new character)
form a new string from the original string where all instances of the original character are replaced by the new character
return the new string.
Write pseudocode for function Replace() .
6 marks
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
| 1 20 | 2 20 | 3 20 | ... | 126 30 | 127 30 | 128 2 |
|---|---|---|---|---|---|---|
20 |
20 |
20 |
30 |
30 |
2 |
|
20 |
20 |
30 |
50 |
30 |
3 |
|
20 |
20 |
40 |
40 |
40 |
4 |
|
20 |
20 |
50 |
40 |
50 |
20 |
|
20 |
3 |
5 |
6 |
60 |
4 |
|
20 |
4 |
2 |
4 |
70 |
30 |
20 20 35 40 46 25
Write pseudocode for procedure Mix() .
Assume Sample and Result are global.
6 marks
Show mark scheme
5(a)(i)
Reasons include: 1 No working software until late in the life cycle so slower to market than competitors // Does not allow the creation of early versions/prototypes (which can be updated later) 2 More difficult/slower to cope with changes to the requirements // website slower to be updated to reflect new requirements 3 Needs high involvement/feedback of the stake holders /customer / client One mark per point Max 2 marks
5(a)(ii) [3 marks]
Iterative / Rapid Application Development / RAD
5(b) [6 marks]
One mark for Stage Stage: Beta testing Max 2 marks for Description Description: 1 Testing carried out by a small group of (potential) users 2 Users will check that the website/software works as required / works in the real world //User will identify errors in the website/software 3 Users will feedback (problems) / suggestions for improvement 4 Problems / suggestions identified are addressed (before the program is sold) PROCEDURE Mix()
A video-conferencing program supports up to six users. Speech from each user is sampled and
digitised (converted from analogue to digital). Digitised values are stored in array Sample .
The array Sample consists of 6 rows by 128 columns and is of type integer. Each row contains
128 digitised sound samples from one user.
The digitised sound samples from each user are to be processed to produce a single value which
will be stored in a 1D array Result of type integer. This process will be implemented by procedure
Mix() .
A procedure Mix() will:
calculate the average of each of the 6 sound samples in a column
ignore sound sample values of 10 or less
store the average value in the corresponding position in
Resultrepeat for each column in array
Sample
The diagram uses example values to illustrate the process:
Sample:
Result:
Show mark scheme
6 [3 marks]
DECLARE Count, Total ThisNum : INTEGER DECLARE ThisUser, ThisSample : INTEGER FOR ThisSample 1 TO 128 Count 0 Total 0 FOR ThisUser 1 TO 6 IF Sample[ThisUser, ThisSample] > 10 THEN Count Count + 1 Total Total + Sample[ThisUser, ThisSample] ENDIF NEXT ThisUser Result[ThisSample] INT(Total / Count) NEXT ThisSample ENDPROCEDURE Mark as follows: 1 Declaration and initialisation before inner loop of and Count Total 2 Outer Loop for 128 iterations 3 Inner loop for six iterations 4 Test for sample > 10 in a loop 5 and if true sum and increment Total Count 6 Calculate average value and assign to array after inner loop Result and within outer loop 7 Use of to convert average to integer INT()/ DIV Max 6 Marks
A function GetNum() will:
- take two parameters: a string and a character
- count the number of times that the character occurs in the string
- 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
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
A procedure Square() will take an integer value in the range 1 to 9 as a parameter and output a
number square.
The boundary of a number square is made up of the character representing the parameter value.
The inside of the number square is made up of the asterisk character ( * ).
Output
| 1 | 2 | 3 | 4 | ... | 9 |
|---|---|---|---|---|---|
1 |
2222 |
333*33333 |
444*4*4**4444444 |
... | 999*9*9**9**9***99**9****9******9*9***9*****9*******************99999999999999999 |
The pseudocode OUTPUT command starts each output on a new line. For example, the following
three OUTPUT statements would result in the outputs as shown:
OUTPUT "Hello"
OUTPUT "ginger"
OUTPUT "cat"
Resulting output:
Hello
ginger
cat
Write pseudocode for procedure Square() .
Parameter validation is not required. 6 marks
Show mark scheme
6 [3 marks]
Example of selection-based solution: PROCEDURE Square(Dim : INTEGER) DECLARE Count : INTEGER CASE OF Dim 1 : OUTPUT "1" 2 : OUTPUT "22" OUTPUT "22" 3 : OUTPUT "333" OUTPUT "33" OUTPUT "333" 4 : OUTPUT "4444" FOR Count 1 TO 2 OUTPUT "44" NEXT Count OUTPUT "4444" 5 : OUTPUT "55555" FOR Count 1 TO 3 OUTPUT "55" NEXT Count OUTPUT "55555" 6 : OUTPUT "666666" FOR Count 1 TO 4 OUTPUT "66" NEXT Count OUTPUT "666666" 7 : OUTPUT "7777777" FOR Count 1 TO 5 OUTPUT "77" NEXT Count OUTPUT "7777777" 8 : OUTPUT "88888888" FOR Count 1 TO 6 OUTPUT "8*8" NEXT Count OUTPUT "88888888" 9 : OUTPUT "999999999" FOR Count 1 TO 7 OUTPUT "9*******9" NEXT Count OUTPUT "999999999" ENDCASE ENDPROCEDURE For in-line / selection-based solutions, mark as follows: 1 Procedure heading and ending including parameter 2 Correct use of parameter to select all required squares 3 Correct output of first two squares 4 At least six squares correctly output 5 At least one loop to output lines with multiple asterisks 6 All number squares output correctly
A program stores a date of birth for a student using a variable, MyDOB, of type DATE .
(a) MyDOB has been assigned a valid value corresponding to Kevin’s date of birth.
Complete the pseudocode statement to test whether Kevin was born on a Thursday.
IF ______ THEN [2]
(b) A function CheckDate() will take three integer parameters representing a day, month and year of a given date.
The function will validate the date of birth for a student that the parameters passed to it represent. For a date to be valid, a student must be at least 18 in year 2020.
(i) Two of the parameter values can be checked without reference to the third parameter. 2 marks
Describe these two checks.
Check 1
Check 2
(ii) Several values of the parameter representing the day can only be checked completely by referring to the value of one other parameter. 2 marks
Describe this check.
Show mark scheme
2(a) [2 marks]
One mark for each underlined part IF DAYINDEX(MyDOB) = 5 THEN
2(b)(i) [2 marks]
MP1 Value for month is between 1 and 12 (inclusive) MP2 Value of year is <= 2002
2(b)(ii)
MP1 Reference to month and day MP2 Clear description for a check that the day number matches with a relevant month (Either day matches with month // month matches with day)
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
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)
A procedure Select() will:
- take two integer values as parameters representing start and end values where both values are greater than 9 and the end value is greater than the start value
- output each integer value between the start and the end value ( not including the start and end values), where the sum of the last two digits is 6, for example, 142.
(a) Write pseudocode for procedure Select() . 7 marks
Parameter validation is not required.
(b) The check performed by procedure Select() on the last two digits is needed at several places in the program and will be implemented using a new function. 4 marks
The new function CheckNum() will:
allow the required sum to be specified (not just 6)
check one number
return an appropriate value.
Describe the function interface and two advantages of this modular approach.
Interface
Advantage 1
Advantage 2
Show mark scheme
6(a) [4 marks]
Max 7 marks PROCEDURE Select(Start, End : INTEGER) DECLARE ThisNum, Total: INTEGER DECLARE ThisString : STRING DECLARE Char1, Char2 : CHAR FOR ThisNum Start+1 TO End-1 ThisString NUM_TO_STR(ThisNum) Char1 RIGHT(ThisString, 1) Char2 LEFT(RIGHT(ThisString, 2), 1) Total STR_TO_NUM(Char1) + STR_TO_NUM(Char2) IF Total = 6 THEN OUTPUT ThisString ENDIF NEXT ThisNum ENDPROCEDURE MP1 Procedure heading and ending MP2 (Count-controlled) Loop MP3 …. with correct range from Start+1 to End-1 MP4 Convert (loop counter) to a string ThisNum MP5 Extract the last two/first/second ’character digit(s)’ required in a loop MP6 Extract the second individual ‘character digit’ required in a loop MP7 Calculate the sum of the last two digits MP8 If sum = 6 then OUTPUT the number (either string or integer) in a loop
6(b)
Max 4 marks MP1 The function will take two integer parameters - the number and the (required) total MP2 … and return a Boolean OR: CheckNum(Number,Total : INTEGER) RETURNS BOOLEAN MP1 MP2 Two marks for the advantages: MP3 can be called repeatedly as and when required CheckNum() MP4 is designed and tested once (then used repeatedly) CheckNum() MP5 Any subsequent change to needs to be made once CheckNum() only // is easier to maintain/modify
A computer shop assembles desktop computers, using items bought from several suppliers. A text
file Stock.txt contains information about each item.
Information for each item is stored as a single line in the Stock.txt file in the format:
<ItemNum><SupplierCode><Description>
||as follows:||
|---|---|---|
||**Format**|**Comment**|
|`ItemNum`|4 numeric characters|unique number for each item in the range “0001”<br>to “5999” inclusive|
|`SupplierCode`|3 alphabetic characters|code to identify the supplier of the item|
|`Description`|a string|a minimum of 12 characters|
The file is organised in ascending order of ItemNum and does not contain all possible values in
the range.
The programmer has defined the first program module as follows:
| Module | Description |
|---|---|
ChangeSupp() |
• called with two parametersCode1 andCode2 of type string that representvalid supplier codes • creates a new file NewStock.txt from the contents of thefile Stock.txt where any reference toCode1 is replaced byCode2• returns a count of the number of items that have had their supplier code changed |
(a) Write pseudocode for module ChangeSupp() . 8 marks
(b) A new module is required: 6 marks
| Module | Description |
|---|---|
Report_1() |
• takes a parameter of type string that represents aSupplierCode• searches the Stock.txt file for each line of item information thatcontains the given SupplierCode• produces a formatted report of items for the given SupplierCode, for example, for supplier DRG, the output could be: Report for Supplier: DRG Item Description 1234 USB Printer Cable 3 m 1273 32GB USB Flash Drive 1350 Mouse Mat 320 x 240 mm Number of items listed: 3 |
Write pseudocode for module Report_1() .
(c) The format of the output from module Report_1() from part (b) is changed. The number of items listed is moved to the top of the report as shown in the example:
Report for Supplier: DRG
Number of items listed: 3
Item Description
1234 USB Printer Cable 3 m
1273 32GB USB Flash Drive
1350 Mouse Mat 320 x 240 mm
(i) Explain why this new layout would increase the complexity of the algorithm. 2 marks
(ii) The algorithm will be modified to produce the report in the new format. The modified algorithm will be implemented so that the file Stock.txt is only read once. 3 marks
Describe the modified algorithm.
Show mark scheme
8(a) [6 marks]
INTEGER DECLARE Count : INTEGER DECLARE ThisLine, ThisCode : STRING OPENFILE "Stock.txt" FOR READ OPENFILE "NewStock.txt" FOR WRITE Count 0 WHILE NOT EOF("Stock.txt") READFILE("Stock.txt ", ThisLine) // brackets optional ThisCode MID(ThisLine, 5, 3) IF ThisCode = Code1 THEN ThisLine LEFT(ThisLine, 4) & Code2 & RIGHT(ThisLine, LENGTH(ThisLine) - 7) Count Count + 1 ENDIF WRITEFILE("NewStock.txt", ThisLine) // brackets optional ENDWHILE CLOSEFILE "NewStock.txt" CLOSEFILE "Stock.txt" RETURN Count ENDFUNCTION MP1 Open both files, in correct modes, and subsequently close MP2 Conditional loop until EOF(“Stock.txt”) MP3 Read a line from AND extract in a loop Stock.txt ThisCode MP4 Test AND if true, increment (must ThisCode = Code1 Count have been Initialised in a loop ) MP5 Update using substring functions and '&' in a loop ThisLine MP6 completely correct update of in a loop ThisLine MP7 Write to in a loop ThisLine NewStock.txt MP8 Return count after loop PROCEDURE Report_1(Supp : STRING)
8(b) [2 marks]
DECLARE Count : INTEGER DECLARE ThisItemNum, ThisDesc, ThisLine, ThisCode : STRING Count 0 OPENFILE "Stock.txt" FOR READ OUTPUT "Report for Supplier:" & Supp OUTPUT "" //Blank line as per example OUTPUT "Item Description" OUTPUT "" //Blank line as per example WHILE NOT EOF("Stock.txt") READFILE("Stock.txt", ThisLine) ThisCode Mid(ThisLine, 5, 3) IF ThisCode = Supp THEN ThisItemNum LEFT(ThisLine, 4) ThisDesc RIGHT(ThisLine, LENGTH(ThisLine) - 7) OUTPUT ThisItem & " " & ThisDesc Count Count + 1 ENDIF ENDWHILE CLOSEFILE "Stock.txt" OUTPUT "" //Blank line as per example OUTPUT "Number of items listed: ", Count ENDPROCEDURE MP1 Output report header (blank lines optional) – Must contain the parameter code MP2 Conditional loop until EOF("Stock.txt") MP3 Read a line from AND extract Stock.txt SupplierCode in a loop MP4 Test if then must SupplierCode = Supp increment count ( have been Initialised ) MP5 Extract AND output item and description in a loop MP6 Output the final line with count
8(c)(i)
Max 2 marks MP1 Must ‘calculate’ the count before any item + description output / after the file is read once MP2 Lines to be output have to be stored … MP3 The file has to be read twice
8(c)(ii) [3 marks]
One mark per point: MP1 Loop through the file calculating the count MP2 Save ‘selected’ items in an array MP3 (After all lines have been read), output the header lines / count MP4 Loop through the array to output each array element
A system is being developed to help manage a car hire business. A customer may hire a car for a number of days.
An abstract model needs to be produced.
(a) Explain the process of abstraction and state four items of data that should be stored each time a car is hired. 3 marks
Explanation
Item 1
Item 2
Item 3
Item 4
(b) Identify two operations that would be required to process the car hire data. 2 marks
Operation 1
Operation 2
Show mark scheme
2(a) [3 marks]
One mark for Explanation: • Abstraction is used to filter out information / data that is not necessary for the task Or the opposite: • To keep only information / data that is necessary for the task One mark for each TWO data items (not dependent on 'Explanation'): Items include: • Car details: ID, Car Registration, car type etc • Customer details: ID, name, address, licence details etc • Start date (of hire) • Return date / Number of days (of hire) • Cost of hire
2(b) [2 marks]
One mark for each ( Max 2 ) Examples include: 1 Input customer details 2 Input car details 3 Input payment details 4 Create hire / start hire 5 Return car / end hire 6 Change / check car status (hired / available / written-off) 7 Cancel hire 8 Process payment / calculate hire cost
A program uses two 1D arrays of type integer. Array1 contains 600 elements and Array2
contains 200 elements.
Array1 contains sample values read from a sensor. The sensor always takes three consecutive
samples and all of these values are stored in Array1 .
A procedure Summarise() will calculate the average of three consecutive values from Array1
and write the result to Array2 . This will be repeated for all values in Array1 .
## } <span class="part-marks">5 marks</span>
The diagram below illustrates the process for the first six entries in Array1 .
# }
| Array2 | |
|---|---|
15 |
|
41 |
|
Write pseudocode for the procedure Summarise() .
Show mark scheme
5 [5 marks]
Mark as follows ( Max 5 ): 1 Procedure heading and ending and declaration of both indexes 2 Loop to process all elements from Array1 3 Sum (any) three consecutive values from and divide by 3 Array1 in a loop 4 Convert result to Integer 5 Assign value to correct element of in a loop Array2 6 Increment index in a loop Array2 PROCEDURE Summarise() DECLARE Value : REAL DECLARE IxA, IxB : INTEGER // Index variables IxB 1 FOR IxA 1 TO 598 STEP 3 Value Array1[IxA] + Array1[IxA + 1] + Array1[IxA + 2] Value Value / 3 Array2[IxB] INT(Value) IxB IxB + 1 NEXT IxA ENDPROCEDURE
A teacher is designing a program to perform simple syntax checks on programs written by students. Student programs are submitted as text files, which are known as project files.
A project file may contain blank lines.
The teacher has defined the first program module as follows:
| Module | Description |
|---|---|
CheckFile() |
• takes the name of an existing project file as a parameter of type string • returns TRUE if the file is valid (it contains at least 10 non-blanklines), otherwise returns FALSE |
(a) Write pseudocode for module CheckFile() . 7 marks
Further modules are defined as follows:
| Module | Description |
|---|---|
CheckLine() |
• takes a line from a project file as a parameter of type string • returns zero if the line is blank or contains no syntax error, otherwise returns an error number as an integer |
CountErrors() |
• takes two parameters: ○ the name of a project file as a string ○ the maximum number of errors as an integer • uses CheckFile() to test the project file. Outputs an errormessage and ends if the project file is not valid • calls CheckLine() for each line in the project file• counts the number of errors • outputs the number of errors or a warning message if the maximum number of errors is exceeded |
(b) CountErrors() is called to check the project file Jim01Prog.txt and to stop if more than 20 errors are found. 2 marks
Write the pseudocode statement for this call.
(c) Write pseudocode for module CountErrors() . Assume CheckFile() and CheckLine() have been written and can be used in your solution. 8 marks
(d) Module CheckLine() includes a check for syntax errors. 2 marks
Two examples of syntax error that cannot be detected from examining a single line are those involving selection and iteration.
Give two other examples.
1
2
Show mark scheme
8(a) [7 marks]
One mark for each point ( Max 7 ) as follows: 1 Function heading and ending including parameter and return type 2 Declaration and initialisation of local Integer for Count 3 OPEN in READ mode and CLOSE 4 Conditional loop until EOF() 5 Read a line in a loop 6 If non-blank, increment count in a loop 7 Terminate loop when 10 non-blank lines have been read 8 Return Boolean in both cases FUNCTION CheckFile(Thisfile : STRING) RETURNS BOOLEAN DECLARE Valid : BOOLEAN DECLARE ThisLine : STRING DECLARE Count : INTEGER Count 0 Valid FALSE OPEN ThisFile FOR READ WHILE NOT EOF(ThisFile) AND Valid = FALSE READFILE ThisFile, ThisLine IF ThisLine <> "" THEN Count Count + 1 IF Count > 9 THEN Valid TRUE ENDIF ENDIF ENDWHILE CLOSEFILE ThisFile RETURN Valid ENDFUNCTION CALL CountErrors("Jim01Prog.txt", 20)
8(b) [2 marks]
One mark for each: 1 Module name, at least one parameter in brackets and one parameter correct 2 Completely correct statement
8(c) [8 marks]
Mark as follows: 1 Procedure heading and ending including parameters 2 Declaration and initialisation of local Integer value for ErrCount 3 Use of , output message and terminate if it returns CheckFile() FALSE 4 Conditional loop until EOF() 5 ...or
ErrCount MaxErrors 6 Read line and use as parameter to in a loop CheckLine() 7 Test return value and increment if non-zero in a loop ErrCount 8 Output either message once only as appropriate PROCEDURE CountErrors(ThisFile : STRING, MaxErrors : INTEGER) DECLARE ErrCount, ThisError : INTEGER DECLARE ThisLine : STRING ErrCount 0 IF CheckFile(ThisFile) = FALSE THEN OUTPUT "That program file is not valid" ELSE OPEN ThisFile FOR READ REPEAT READFILE, ThisFile, ThisLine ThisError CheckLine(ThisLine) IF ThisError <> 0 THEN ErrCount ErrCount + 1 ENDIF UNTIL ErrCount > MaxErrors OR EOF(ThisFile) IF EOF(ThisFile) = FALSE THEN OUTPUT "Check terminated – too many errors" ELSE OUTPUT "There were ", ErrCount, " errors." ENDIF CLOSEFILE ThisFile ENDIF ENDPROCEDURE
8(d) [2 marks]
One mark for each ( Max 2 ): Examples: 1 Incorrect block structure. Missing keyword denoting part of block (for example ) ENDPROCEDURE, ENDFUNCTION, ENDTYPE 2 Data type errors, for example, assigning an integer value to a string 3 Identifier used before it is declared 4 Incorrect parameter use
(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
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
Examine the following pseudocode.
IF A = TRUE THEN
IF B = TRUE THEN
IF C = TRUE THEN
CALL Sub1()
ELSE
CALL Sub2()
ENDIF
ENDIF
ELSE
IF B = TRUE THEN
IF C = TRUE THEN
CALL Sub4()
ELSE
CALL Sub3()
ENDIF
ELSE
IF C = FALSE THEN
CALL Sub3()
ELSE
CALL Sub4()
ENDIF
ENDIF
ENDIF
A programmer wants to re-write the pseudocode as four separate IF...THEN...ENDIF
statements, each containing a single CALL statement. This involves writing a single, simplified
logic expression as the condition in each statement.
Write the amended pseudocode.
1
2
3
4 4 marks
Show mark scheme
5 [4 marks]
One mark per clause: IF...THEN...ENDIF 1 IF A AND B AND C THEN CALL Sub1() ENDIF 2 IF (A AND B) AND NOT C THEN CALL Sub2() ENDIF 3 IF (NOT A) AND (NOT C) THEN CALL Sub3() ENDIF 4 IF (NOT A) AND C THEN CALL Sub4() ENDIF
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.
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
(a) A text string contains three data items concatenated as shown:
<StockID><Description><Cost>
Item lengths are:
| Item | Length |
|---|---|
| StockID | 5 |
| Description | 32 |
| Cost | the remainder of the string |
A procedure Unpack() takes four parameters of type string. One parameter is the original
text string. The other three parameters are used to represent the three data items shown in
the table and are assigned values within the procedure. These values will be used by the
calling program after the procedure ends.
(i) Write pseudocode for the procedure Unpack() . 6 marks
(ii) Explain the term procedure interface with reference to procedure Unpack() . 2 marks
(b) The design changes and a record structure is defined to store the three data items.
A user-defined data type StockItem is created as shown:
TYPE StockItem
DECLARE StockID : STRING
DECLARE Description : STRING
DECLARE Cost : REAL
ENDTYPE
(i) A variable LineData of type StockItem is declared. 1 mark
Write the pseudocode statement to assign the value 12.99 to the Cost field of
LineData .
(ii) Procedure Unpack() is modified and converted to a function which takes the original text string as the only parameter. 2 marks
Explain the other changes that need to be made to convert the procedure into a function.
(c) Unpack() is part of a program made up of several modules. During the design stage, it is important to follow good programming practice. One example of good practice is the use of meaningful identifier names. 3 marks
Give the reason why this is good practice. Give two other examples of good practice.
Reason
Example 1
Example 2
(d) The program that includes Unpack() is tested using the walkthrough method. 3 marks
Describe this method and explain how it can be used to identify an error.
Show mark scheme
5(a)(i) [6 marks]
One mark per point: 1 Procedure heading and ending including four parameters... 2 ...and use of for the three extracted values BYREF 3 Extract and assign SID 4 Extract and assign SDesc 5 Calculation of length of (remainder of string) SCost 6 Extract and assign following an attempt at MP5 SCost PROCEDURE UnPack(BYVAL TLine : STRING, BYREF SID, SDesc, SCost : STRING) SID LEFT(TLine, 5) SDesc MID(TLine, 6, 32) SCost RIGHT(TLine, LENGTH(TLine) – 37) ENDPROCEDURE
5(a)(ii) [2 marks]
One mark each ( Max 2 ): 1 Provides a mechanism to allow calling program to pass data 2 Defines the four parameters of Unpack() 3 … giving their data type and order
5(b)(i) [1 mark]
LineData.Cost 12.99
5(b)(ii) [2 marks]
One mark per point ( Max 2 ): • The new function will return an item of type StockItem • Need to declare/use a (local) variable of type StockItem • field needs to be converted from a string to a real Cost
5(c) [3 marks]
One mark for reason One mark for each example ( Max 2 ) Reason: • Makes the code easier to understand // Describes the purpose of the identifier // Makes the code easier to debug/test/maintain Further examples include: • White space • Indentation • Keywords in capitals • Comments • Local variables // parameters
5(d) [3 marks]
One mark per point ( Max 3 ) 1 The program is checked by creating a trace table / going through the program a line at a time 2 ….to record/check variable (values) as they change 3 Error may be indicated when variable given an unexpected value 4 Error may be indicated by an unexpected path through the program // Faults in the logic of the program can be detected
(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.
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
Study the following pseudocode. Line numbers are for reference only.
10 PROCEDURE Encode()
11 DECLARE CountA, CountB, ThisNum : INTEGER
12 DECLARE ThisChar : CHAR
13 DECLARE Flag : BOOLEAN
14 CountA 0
15 CountB 10
16 Flag TRUE
17 INPUT ThisNum
18 WHILE ThisNum <> 0
19 ThisChar LEFT(NUM_TO_STR(ThisNum), 1)
20 IF Flag = TRUE THEN
21 CASE OF ThisChar
22 '1' : CountA CountA + 1
23 '2' : IF CountB < 10 THEN
24 CountA CountA + 1
25 ENDIF
26 '3' : CountB CountB - 1
27 '4' : CountB CountB - 1
28 Flag FALSE
29 OTHERWISE : OUTPUT "Ignored"
30 ENDCASE
31 ELSE
32 IF CountA > 2 THEN
33 Flag NOT Flag
34 OUTPUT "Flip"
35 ELSE
36 CountA 4
37 ENDIF
38 ENDIF
39 INPUT ThisNum
40 ENDWHILE
41 OUTPUT CountA
42 ENDPROCEDURE
(a) Procedure Encode() contains a loop structure. 2 marks
Identify the type of loop and state the condition that ends the loop.
Do not include pseudocode statements in your answer.
Type
Condition
(b) Complete the trace table below by dry running the procedure Encode() when the following values are input: 6 marks
12, 24, 57, 43, 56, 22, 31, 32, 47, 99, 0
The first row is already complete.
| ThisNum | ThisChar | CountA | CountB | Flag | OUTPUT |
|---|---|---|---|---|---|
0 |
10 |
TRUE |
|||
(c) Procedure Encode() is part of a modular program. Integration testing is to be carried out on the program. 2 marks
Describe integration testing .
Show mark scheme
5 (Attempt to) use hyphens to link three groups
5(a) [6 marks]
: pre-condition : when the value of / the input value is equal to zero ThisNum
5(b)
ThisNum ThisChar CountA CountB Flag OUTPUT 0 10 TRUE 12 '1' 1 24 '2' 57 '5' "Ignored" 43 '4' 9 FALSE '5' 56 4 22 '2' TRUE "Flip" '3' 31 8 32 '3' 7 47 '4' 6 FALSE 99 '9' TRUE "Flip" 0 4 no marks per group then mark by columns (columns 3 to 6) for max 4
5(c) [7 marks]
Modules that have already been tested individually are combined into a single (sub) program which is then tested as a whole
(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
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
(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() .
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
The following pseudocode represents an algorithm intended to output the last three lines as they appear in a text file. Line numbers are provided for reference only.
10 PROCEDURE LastLines(ThisFile : STRING)
11 DECLARE ThisLine : STRING
12 DECLARE Buffer : ARRAY[1:3] OF STRING
13 DECLARE LineNum : INTEGER
14 LineNum 1
15 OPENFILE ThisFile FOR READ
16
17 WHILE NOT EOF(ThisFile)
18 READFILE Thisfile, ThisLine // read a line
19 Buffer[LineNum] ThisLine
20 LineNum LineNum + 1
21 IF LineNum = 4 THEN
22 LineNum 1
23 ENDIF
24 ENDWHILE
25
26 CLOSEFILE ThisFile
27 FOR LineNum 1 TO 3
28 OUTPUT Buffer[LineNum]
29 NEXT LineNum
30 ENDPROCEDURE
(a) There is an error in the algorithm. In certain cases, a text file will have at least three lines but the output will be incorrect.
(i) State how the output may be incorrect. 1 mark
(ii) Describe the error in the algorithm and explain how it may be corrected. 4 marks
Description
Explanation
(b) The original algorithm is implemented and sometimes the last three lines of the text file are output correctly. 1 mark
State the condition that results in the correct output.
(c) Lines 20 to 23 inclusive could be replaced with a single pseudocode statement. 2 marks
Write the pseudocode statement.
Show mark scheme
7(a)(i) [1 mark]
The lines are output in an incorrect sequence / in the wrong order / not as they appear in the file
7(a)(ii) [4 marks]
Description of error: (Max 2 marks) If the final line of the file is not written into array element 3 then outputting the elements in the sequence 1 to 3 will give the error. Explanation of error correction: (Max 2 marks) Attempt at description of 'shuffle' Copy Buffer[2] to Buffer[1] AND copy Buffer[3] to Buffer[2] Read a line from the file and write it to Buffer[3] OR Store the index of the last element written to buffer (the last line of the file) Replace the FOR loop with something that starts at index and then wraps around (MOD 3) OR (two-loop solution, not using an array) Loop to read file to end to get number of lines close and re-open file read (and discard) lines to number of lines - 3, then loop to read and output last 3 lines
7(b) [2 marks]
If the number of lines in the text file is a multiple of three
7(c)
Correct answers include: LineNum (LineNum MOD 3) + 1 // ((LineNum + 3) MOD 3)
- 1 One mark for assignment to making any use of LineNum MOD One for completely correct statement
The following is a procedure design in pseudocode.
Line numbers are given for reference only.
10 PROCEDURE Check(InString : STRING)
11 DECLARE Odds, Evens, Index : INTEGER
12
13 Odds 0
# ←
14 Evens 0
# ←
15 Index 1
# ←
16
17 WHILE Index <= LENGTH(InString)
18 IF STR_TO_NUM(MID(InString, Index, 1)) MOD 2 <> 0 THEN
19 Odds Odds + 1
# ←
20 ELSE
21 Evens Evens + 1
# ←
22 ENDIF
23 Index Index + 1
# ←
24 ENDWHILE
25
26 CALL Result(Odds, Evens)
27 ENDPROCEDURE
(a) Complete the following table by giving the answers, using the given pseudocode.
| Answer | |
|---|---|
| A line number containing a variable being incremented | |
| The type of loop structure | |
| The number of functions used | |
The number of parameters passed toSTR_TO_NUM() |
|
The name of a procedure other thanCheck() |
(b) The pseudocode includes several features that make it easier to read and understand. 5 marks 3 marks
Identify three of these features. 1
2
3 (c) (i) The loop structure used in the pseudocode is not the most appropriate. 2 marks
State a more appropriate loop structure and justify your choice.
Loop structure
Justification
(ii) The appropriate loop structure is now used. Two lines of pseudocode are changed and two lines are removed. 1 mark
Write the line numbers of the two lines that are removed.
Show mark scheme
4(a) [5 marks]
A line number containing a variable being incremented 19 / 21 / 23 The type of loop pre-condition structure The number of functions used 3 The number of parameters passed to function 1 STR_TO_NUM() The name of a procedure other than Result Check()
4(b) [2 marks]
One mark per point: Meaningful variable names • Indentation / white space / blank lines • Capitalisation of keywords •
4(c)(i) [1 mark]
One mark per point: Structure: A count-controlled loop Justification: The number of iterations is known // repeats for the length of InString
4(c)(ii) [7 marks]
15, 23 One mark for both line numbers
Study the following pseudocode. Line numbers are for reference only.
10 FUNCTION Convert(Name : STRING) RETURNS STRING
11
12 DECLARE Flag: BOOLEAN
13 DECLARE Index : INTEGER
14 DECLARE ThisChar : CHAR
15 DECLARE NewName : STRING
16
17 CONSTANT SPACECHAR = ' '
18
19 Flag TRUE
20 Index 1
21 NewName "" // formatted name string
22
23 WHILE Index <= LENGTH(Name)
24 ThisChar MID(Name, Index, 1)
25 IF Flag = TRUE THEN
26 NewName NewName & UCASE(ThisChar)
27 IF ThisChar <> SPACECHAR THEN
28 Flag FALSE
29 ENDIF
30 ELSE
31 NewName NewName & ThisChar
32 ENDIF
33 IF ThisChar = SPACECHAR THEN
34 Flag TRUE
35 ENDIF
36 Index Index + 1
37 ENDWHILE
38
39 RETURN NewName
40
41 ENDFUNCTION
(a) Complete the trace table below by dry running the function when it is called as follows: 5 marks
Result Convert(" ∇ in ∇ a ∇∇ Cup")
Note: The symbol ' ∇ ' has been used to represent a space character.
Use this symbol for any space characters in the trace table.
| The first row has been | completed for | you. | ||
|---|---|---|---|---|
Name |
Flag |
Index |
NewName |
ThisChar |
"∇in∇a∇∇Cup" |
||||
(b) The pseudocode for Convert() contains a conditional loop. 2 marks
State a more appropriate loop structure.
Justify your answer.
Loop structure
Justification
(c) Two changes need to be made to the algorithm.
Change 1: Convert to lower case any character that is not the first character after a space. Change 2: Replace multiple spaces with a single space.
(i) Change 1 may be implemented by modifying one line of the pseudocode. 1 mark
Write the modified line.
(ii) Change 2 may be implemented by moving one line of the pseudocode. 2 marks
Write the number of the line to be moved and state its new position.
Line number
New position
Show mark scheme
4(a) [2 marks]
Name Flag Index NewName ThisChar ∇ ∇ ∇∇ " in a Cup" TRUE 1 "" ∇ ' ' ∇ " " 2 'i' FALSE ∇ " I" 3 'n' ∇ " In" ∇ 4 ' ' ∇ ∇ TRUE " In " 5 'a' ∇ ∇ FALSE " In A" 6 ∇ ' ' TRUE ∇ ∇ ∇ " In A " 7 ∇ ' ' ∇ ∇ ∇∇ " In A " 8 'C' ∇ ∇ ∇∇ FALSE " In A C" 9 'u' ∇ ∇ ∇∇ " In A Cu" 10 'p' ∇ ∇ ∇∇ " In A Cup" FALSE 11 'p' ∇ ∇ ∇∇ " In A Cup" Mark as follows: One mark for each of columns 2 to 5 (condone missing final 11) • One mark for final row all correct (including final 11) •
4(b)
Loop structure: A count-controlled loop Justification: The number of iterations is known One mark per point
4(c)(i) [1 mark]
A couple of solutions: ← 24 ThisChar LCASE(MID(Name, Index, 1) ALTERNATIVE: ← 31 NewName NewName & LCASE(ThisChar) Ignore line number
4(c)(ii) [2 marks]
One mark for each: Line number: 26 New position: Move to after line 27 / line 28
A teacher uses a paper-based system to store marks for a class test. The teacher requires a program to assign grades based on these results.
The program will output the grades together with the average mark.
Write a detailed description of the algorithm that will be needed. 6 marks
Show mark scheme
4 [6 marks]
Marks awarded for a description of each of the following steps of the algorithm: 1 Reference variables for of students and marks Count Total 2 Loop through all students ( ) Count 3 Input individual mark (in loop) 4 Compare mark with threshold / boundary values to determine grade (in loop) 5 Output the grade for a student (in loop) 6 Maintain a (and if required) (in loop) Total Count 7 Calculate average by dividing by and Output ( after loop ) Total Count Note: Max 6 marks
(a) A student is learning about arrays.
She wants to write a program to:
declare a 1D array
RNumof 100 elements of typeINTEGERassign each element a random value in the range 1 to 200 inclusive
count and output how many numbers generated were between 66 and 173 inclusive.
(i) Write pseudocode to represent the algorithm. 6 marks
(ii) The student decides to modify the algorithm so that each element of the array will contain a unique value. 3 marks
Describe the changes that the student needs to make to the algorithm.
Show mark scheme
5(a)(i)
DECLARE RNum : ARRAY[1:100] OF INTEGER DECLARE Index, Count : INTEGER ← Count 0 ← FOR Index 1 TO 100 ← RNum[Index] INT(RAND(200)) + 1 IF RNum[Index] >= 66 AND RNum[Index] <= 173 THEN ← Count Count + 1 ENDIF NEXT Index OUTPUT Count Mark as follows: 1 Array declaration 2 Loop for 100 iterations 3 Array element index 'syntax' (left-hand side of assignment expression) in a loop 4 Use of to generate value in range (and assign to array RAND() element) in a loop 5 Check if random number within range and if so, increment count in a loop 6 Output of count (following a reasonable attempt) after the loop
5(a)(ii) [4 marks]
One mark per bullet / sub-bullet point 1 Initialise the array to a rogue value (to indicate 'unassigned' element) 2 Add a conditional loop to: 3 Generate and store a random number (in the correct range) 4 Check the stored number against values already in the array 5 If the stored number is found then generate another random value 6 Otherwise add it to the array (and exit loop) Note: Max 3 marks
5(b)(i) [2 marks]
Give a line number containing an example of an 07 initialisation statement. Give a line number containing the start of a repeating 09 / 10 block of code. Give a line number containing a logic statement. 12 3 Give the number of parameters of function . MID() One mark for each row
5(b)(ii) [8 marks]
IF (NextChar >= 'a') AND (NextChar <= 'z') THEN One mark for IF ... AND ... One mark for both conditions
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
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
Study the following pseudocode. Line numbers are for reference only.
10 FUNCTION Convert(Name : STRING) RETURNS STRING
11
12 DECLARE Flag: BOOLEAN
13 DECLARE Index : INTEGER
14 DECLARE ThisChar : CHAR
15 DECLARE NewName : STRING
16
17 CONSTANT SPACECHAR = ' '
18
19 Flag TRUE
20 Index 1
21 NewName "" // formatted name string
22
23 WHILE Index <= LENGTH(Name)
24 ThisChar MID(Name, Index, 1)
25 IF Flag = TRUE THEN
26 NewName NewName & UCASE(ThisChar)
27 IF ThisChar <> SPACECHAR THEN
28 Flag FALSE
29 ENDIF
30 ELSE
31 NewName NewName & ThisChar
32 ENDIF
33 IF ThisChar = SPACECHAR THEN
34 Flag TRUE
35 ENDIF
36 Index Index + 1
37 ENDWHILE
38
39 RETURN NewName
40
41 ENDFUNCTION
(a) Complete the trace table below by dry running the function when it is called as follows: 5 marks
Result Convert(" ∇ in ∇ a ∇∇ Cup")
Note: The symbol ' ∇ ' has been used to represent a space character.
Use this symbol for any space characters in the trace table.
| The first row has been | completed for | you. | ||
|---|---|---|---|---|
Name |
Flag |
Index |
NewName |
ThisChar |
"∇in∇a∇∇Cup" |
||||
(b) The pseudocode for Convert() contains a conditional loop. 2 marks
State a more appropriate loop structure.
Justify your answer.
Loop structure
Justification
(c) Two changes need to be made to the algorithm.
Change 1: Convert to lower case any character that is not the first character after a space. Change 2: Replace multiple spaces with a single space.
(i) Change 1 may be implemented by modifying one line of the pseudocode. 1 mark
Write the modified line.
(ii) Change 2 may be implemented by moving one line of the pseudocode. 2 marks
Write the number of the line to be moved and state its new position.
Line number
New position
Show mark scheme
4(a) [2 marks]
Name Flag Index NewName ThisChar ∇ ∇ ∇∇ " in a Cup" TRUE 1 "" ∇ ' ' ∇ " " 2 'i' FALSE ∇ " I" 3 'n' ∇ " In" ∇ 4 ' ' ∇ ∇ TRUE " In " 5 'a' ∇ ∇ FALSE " In A" 6 ∇ ' ' TRUE ∇ ∇ ∇ " In A " 7 ∇ ' ' ∇ ∇ ∇∇ " In A " 8 'C' ∇ ∇ ∇∇ FALSE " In A C" 9 'u' ∇ ∇ ∇∇ " In A Cu" 10 'p' ∇ ∇ ∇∇ " In A Cup" FALSE 11 'p' ∇ ∇ ∇∇ " In A Cup" Mark as follows: One mark for each of columns 2 to 5 (condone missing final 11) • One mark for final row all correct (including final 11) •
4(b)
Loop structure: A count-controlled loop Justification: The number of iterations is known One mark per point
4(c)(i) [1 mark]
A couple of solutions: ← 24 ThisChar LCASE(MID(Name, Index, 1) ALTERNATIVE: ← 31 NewName NewName & LCASE(ThisChar) Ignore line number
4(c)(ii) [2 marks]
One mark for each: Line number: 26 New position: Move to after line 27 / line 28