9.2 Algorithms (AS)
AS Level · 64 questions found
What this topic covers
Section titled “What this topic covers”- An algorithm is a solution expressed as defined steps
- Identifier tables; write pseudocode with input, process, output
- Three basic constructs: sequence, selection, iteration
- Document using structured English, flowcharts or pseudocode; convert between them
- Stepwise refinement; logic statements in algorithm design
Past paper questions
Section titled “Past paper questions”Data is a global 1D array containing 30 elements of type STRING
An algorithm will output:
all non-blank elements (elements that do not contain an empty string)
the final total of the number of elements output.
Complete the program flowchart to represent the algorithm:
START
END 5 marks
Show mark scheme
2 Alternative solution Checking for empty string first
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 program is being designed in pseudocode.
The program contains the following declaration for the global array MyData:
DECLARE MyData : ARRAY[1:10000] OF STRING
A function FindFirst() is written to search the array for a given string and to return the index of the first element where that string is found, or to return –1 if the string is not found.
The function is written in pseudocode as shown:
FUNCTION FindFirst(SearchString : STRING) RETURNS INTEGER DECLARE Index, FoundAt : INTEGER FoundAt –1 FOR Index 1 TO 10000 IF MyData[Index] = SearchString THEN // outer conditional clause IF FoundAt = –1 THEN // inner conditional clause FoundAt Index ENDIF ENDIF NEXT Index RETURN FoundAt ENDFUNCTION
(a) (i) Comment on why the programmer chose –1 as the initial value of FoundAt 1 mark
(ii) Explain the purpose of the outer conditional clause. 1 mark
(iii) The inner conditional clause ensures that only the index of the first matching element, if any, is returned. 1 mark
Explain how this clause works.
(b) The pseudocode does not use the most appropriate loop construct.
(i) Explain why this is not the most appropriate loop construct. 1 mark
(ii) Suggest and justify a more appropriate loop construct that could be used. 2 marks
Construct
Justification
Show mark scheme
5(a)(i) [1 mark]
It is a value that is invalid as an (array) index // not in the range of valid (index) values
5(a)(ii) [1 mark]
To test whether the current element / value at index matches the given / search string / data / parameter
5(a)(iii) [1 mark]
The value of is only updated to the (current) index if it currently FoundAt stores the initial value / -1 // is not updated when it currently stores any other value than -1 FoundAt
5(b)(i) [1 mark]
The loop continues after the (first instance) of the search value / string / matching element has been found Comparisons/tests continue to be made even if the search value / string / matching element has been found
5(b)(ii) [2 marks]
One mark per point Construct: A conditional loop Justification: The loop / search can be terminated as soon as the (first occurrence of) / required value / required SearchString string / matching element is found
Students are learning about a simple check digit method for data validation. In this method, a single check digit is appended to the end of an original number to give a new number.
The students are studying a method which:
calculates the sum of all the digits in the original number
uses integer division to calculate the remainder when the sum is divided by 10
uses the remainder as the check digit
appends the check digit to the original number, creating the new number.
For example:
| original number | 4162 |
|---|---|
| sum of all digits | 4 + 1 + 6 + 2 = 13 |
| remainder when the sum is divided by 10 using integer division | 3 |
| new number | 41623 |
The method described can be used to detect single-digit errors. For example, if the new number is incorrectly input as 41633, then the check digit does not match and the input will be rejected.
(a) An incorrect attempt was made to enter 41623. The first two digits were entered incorrectly; the last three digits were entered correctly. 2 marks
When this number was tested, the check digit was found to be correct and the input was accepted.
Identify an example of the incorrect attempt to enter 41623 and explain why this number would not be rejected.
Number
Explanation
(b) A module Generate() will take an integer value representing an original number and return an integer value representing a new number which includes the check digit. 7 marks
The original number is always at least three digits in length.
Write pseudocode for the module Generate()
Assume that the parameter is valid.
Show mark scheme
6(a) [2 marks]
Number: Any number where the first two digits sum to 5 / 15 and the last three digits are 623 Explanation: The remainder is the same / 3 // The sum of the (first four) digits is the same / 13
6(b)
Example Solution – no conversion to string FUNCTION Generate(Number : INTEGER) RETURNS INTEGER DECLARE Total, CheckDigit, Remainder, Num: INTEGER Num Number Total 0 WHILE Num > 0 Remainder Num MOD 10 Num Num DIV 10 Total Total + Remainder ENDWHILE CheckDigit Total MOD 10 Number Number * 10 + CheckDigit RETURN Number ENDFUNCTION Mark as follows: 1 Function heading, parameters return type and ending 2 Initialise Total 3 Loop while Num > 0 4 attempt to use MOD and DIV to sum successive digits in Number 5 completely correct sum of digits 6 Calculate CheckDigit 7 Add to original number and return number CheckDigit
Data is a global 1D array containing 20 elements of type REAL
An algorithm will:
input a sequence of real values, one at a time
assign each value to consecutive array elements, starting from index 1
end when the value 99.9 is input, or all 20 elements have been assigned (the value 99.9 must not be stored in the array).
Complete the program flowchart to represent the algorithm:
START
END 5 marks
Show mark scheme
2 Alternative solution:
A text file OldFile.txt contains IDs, names and email addresses for members of a club. Three information items are stored for each member and each item is stored on a separate line.
The example shows the information for the first two members in the first six lines of the file:
| Line in file | Information item | Example data |
|---|---|---|
| 1 | member 1 ID | "AB1234" |
| 2 | member 1 name | "Freddie Jones" |
| 3 | member 1 email address | "FreddieJ909@Cambridge.org" |
| 4 | member 2 ID | "BC2345" |
| 5 | member 2 name | "Sue Smith" |
| 6 | member 2 email address | "Sue1024@Cambridge.org" |
The member ID string is always two letters followed by four digits.
The file design is to be changed so that information for each user is stored as a single line of the file, with the character '' used as a separator between data items.
For example, the single line for member 1 will be:
"AB1234\Freddie Jones\FreddieJ909@Cambridge.org"
An algorithm will produce a new file NewFile.txt from the contents of OldFile.txt
Assume:
LineX, LineY and LineZ are of type STRING and are used to store the three items of information for each member
NewString is a temporary variable of type STRING
OldFile.txt exists and contains valid data.
(a) The algorithm to create the new file is expressed in steps. 6 marks
Complete the following numbered steps:
Step 1 : open the file ______ in
Step 2 : open the file ______ in
Step 3 : read a line from ______ and store in
Step 4 : read a line from ______ and store in
Step 5 : read a line from ______ and store in
Step 6 : set NewString to
Step 7 : write NewString to
Step 8 : repeat from step ______ until
Step 9 : close both files.
(b) The character '' has been chosen as a separator. 1 mark
Explain why this is a suitable character.
(c) Two new information items are to be stored for each member. Both new items are encrypted; they can each contain any character (including '') and can be of any length up to a maximum of 99 characters. 3 marks
For example:
| Information item | Example data |
|---|---|
| member 1 ID | "AB1234" |
| member 1 name | "Freddie Jones" |
| member 1 email address | "FreddieJ909@Cambridge.org" |
| member 1 new information 1 | "En/98&*( |
| member 1 new information 2 | "23\CoboL" |
Explain the additional file design changes needed so that:
all the information items for each member are stored on a single line of NewFile.txt
it is possible to extract each information item after the line is read.
Assume the '' character is not used in any email address.
Show mark scheme
3(a) [6 marks]
Mark as follows: MP1 1 OldFile.txt read (mode) open the file in MP2 2 NewFile.txt write (mode) open the file in 3 OldFile.txt in read a line from and store LineX MP3 4 OldFile.txt read a line from and store in LineY OldFile.txt 5 read a line from and store in LineZ MP4 6 set to NewString LineX & '' & LineY & '' & LineZ MP5 7 NewFile.txt write to NewString MP6 8 3 end of OldFile.txt repeat from step until 9 close both files
3(b) [1 mark]
It does not appear in (any of) the data items // it does not appear in the ID and Name
3(c) [3 marks]
MP1 Add a ( single) new separator at the end of the third (original) item MP2 Calculate the length of both new data items MP3 Store / append the length (of the new each items) MP4 as a fixed length / separated digit string // by example Max 3
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) A program contains a global 1D array of type STRING containing 65 elements. 6 marks
An existing text file is used to store the data in the array. Only non-blank elements (those that do not contain an empty string) are written to the text file.
An algorithm will:
write the first element of the array as a new line in the text file
continue until all elements have been written, each to a new line of the text file.
Stepwise refinement is applied to the algorithm.
Describe up to six steps for this algorithm that could be used to produce pseudocode.
Do not use pseudocode statements in your answer.
Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
(b) Iteration is one programming construct.
Identify one other programming construct that will be required when the algorithm from part
(a) is converted into pseudocode and explain how it is used. 2 marks
Construct
Use
Show mark scheme
2(a) [6 marks]
One mark per point: 1 Open the file in append mode (and subsequently close) before loop 2 Initialise a variable to 1 / 0 before loop 3 Use the variable as an index to the array to access an element in a loop 4 Test if element value is blank / empty in a loop 5 If not blank then write the value to the file in a loop 6 Increment the variable in a loop 7 Repeat from MP3 until variable value is 66 / 65 / all elements (in the array) have been checked Max 6
2(b) [2 marks]
One mark per point: Construct: Selection Use: To test whether the (array) element is blank Alternative: Construct: Sequence Use: To specify the order in which the steps of the algorithm have to be followed so that the task is completed correctly
A program uses a stack to hold up to 30 integer values. The stack is implemented using a global integer variable and a global 1D array.
The array is declared in pseudocode: DECLARE ThisStack : ARRAY[1:30] OF INTEGER
Stack design notes:
The global variable SP acts as a stack pointer. SP contains the array index of the last value pushed onto the stack.
If the stack is empty, then SP is assigned the value zero.
The first item added to the stack will be stored in ThisStack[1]
SP is incremented each time an item is added to the stack.
A function Pop() is written to remove an item from ThisStack. The function returns an item of type PopData which is defined in pseudocode:
TYPE PopData DECLARE Data : INTEGER DECLARE Exists : BOOLEAN ENDTYPE
The value removed from the stack is assigned to Data and Exists is set to TRUE. If it is not possible to remove a value from the stack, then Exists is set to FALSE
Complete the pseudocode for Pop()
FUNCTION Pop() RETURNS PopData
DECLARE ThisPop :
IF ______ THEN
PopData.Exists ______ // Stack is empty
ELSE
PopData.Data
PopData.Exists
SP
ENDIF
RETURN ThisPop
ENDFUNCTION 5 marks
Show mark scheme
3 [5 marks]
FUNCTION Pop() RETURNS PopData MP 2 DECLARE ThisPop : PopData MP 3 IF SP < 1 // SP = 0 THEN MP 1 PopData.Exists FALSE // Stack is empty ELSE MP 4 PopData.Data ThisStack[SP] MP 1 PopData.Exists TRUE MP 5 SP SP – 1 ENDIF RETURN ThisPop` ENDFUNCTION Mark as follows: MP 1 One mark for both assignments to ( and PopData.Exists FALSE ) TRUE MP 2, 3, 4 ,5 One mark for each of remaining four bold parts
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
Students are learning about a simple check digit method for data validation. In this method, a single check digit is appended to the end of an original number to give a new number.
The students are studying a method which:
calculates the sum of all the digits in the original number
uses integer division to calculate the remainder when the sum is divided by 10
uses the remainder as the check digit
appends the check digit to the original number, creating the new number.
For example:
| original number | 4162 |
|---|---|
| sum of all digits | 4 + 1 + 6 + 2 = 13 |
| remainder when the sum is divided by 10 using integer division | 3 |
| new number | 41623 |
The original number is always at least three digits in length.
When the new number is input, the check digit is used to validate the new number.
(a) A function Generate() is written to take an original number as a parameter and to return the check digit. 2 marks
Outline a test plan that could be used to fully test function Generate()
Assume that the parameter is valid.
(b) A function CheckNumber() will take an integer value and return the Boolean value TRUE if the check digit is correct, otherwise return FALSE Write pseudocode for the function CheckNumber() 7 marks
Assume that the parameter is valid.
Show mark scheme
6(a) [2 marks]
One mark per point: 1 Create a list of numbers that should generate all of the possible check digit values 2 and check that each / the / a generated value is as expected
6(b)
Example solution – numeric version FUNCTION CheckNumber(Number : INTEGER) RETURNS BOOLEAN DECLARE Sum, CheckDigit, Remainder: INTEGER Remainder Number MOD 10 Number Number DIV 10 CheckDigit Remainder Sum 0 WHILE Nummer > 0 Remainder Number MOD 10 Number Number DIV 10 Total Total + Remainder ENDWHILE IF Total MOD 10 <> CheckDigit THEN RETURN FALSE ENDIF RETURN TRUE ENDFUNCTION 1 Function Header including Identifier, parameters and return type 2 Initialise Sum 3 Set to least significant digit in Number CheckDigit 4 Loop while
0 Number 5 attempt to use MOD and DIV to sum successive digits in in loop Number 6 completely correct sum of all digits in apart from least significant Number digit in loop 7 Calculate check digit from sum 8 Compare with and return appropriate Boolean value CheckDigit Max 7
A program stores 20 unique random integers between 0 and 100 (inclusive) in a 1D array that is local to the main program.
(a) Write program code to declare the array local to the main program and store 20 unique random numbers between 0 and 100 (inclusive) in the array. 3 marks
Save your program as Question2_N25 .
Copy and paste the program code into part 2(a) in the evidence document.
(b) The procedure PrintArray() takes an integer array as a parameter. The procedure outputs the array contents on a single line with a space between each integer. 3 marks
Write the program code for PrintArray()
Save your program.
Copy and paste the program code into part 2(b) in the evidence document.
(c) The function BubbleSort() : 5 marks
takes an integer array as a parameter
sorts the data into ascending order using a bubble sort
returns the sorted array.
The function needs to work for an array of any length.
Do not use an inbuilt sorting method.
Write program code for BubbleSort()
Save your program.
Copy and paste the program code into part 2(c) in the evidence document. (d) (i) The main program:
outputs the contents of the array using
PrintArray()sorts the array using
BubbleSort()outputs
"Sorted"outputs the contents of the sorted array using
PrintArray()
Write program code for the main program.
Save your program.
Copy and paste the program code into part 2(d)(i) in the evidence document.
(ii) Test your program. 3 marks
Take a screenshot of the output(s).
Save your program.
Copy and paste the screenshot(s) into part 2(d)(ii) in the evidence document.
(e) The recursive function RecursiveBinarySearch() takes four parameters: 1 mark 6 marks
an integer array
the lower bound of the array
the upper bound of the array
the value to find in the array.
The recursive function performs a binary search to find the index of the value in the array.
The function returns the index of the value if it is found. The function returns –1 if the value is
not found.
Write program code for RecursiveBinarySearch()
Save your program.
Copy and paste the program code into part 2(e) in the evidence document.
(f) (i) The main program: 3 marks
prompts the user to enter an integer
takes the integer as input
calls
RecursiveBinarySearch()with the sorted array, appropriate lower bound, appropriate upper bound and the user’s input as parametersoutputs
"Not found"if the input is not within the arrayoutputs
"Found at position"and the index if the input is within the array.
Write program code to amend the main program.
Save your program.
Copy and paste the program code into part 2(f)(i) in the evidence document.
(ii) Test your program three times with each of the inputs described: 2 marks
Test 1: the smallest number in the array
Test 2: the largest number in the array
Test 3: a number not in the array
Take a screenshot of each output.
Save your program.
Copy and paste the screenshot(s) into part 2(f)(ii) in the evidence document.
Show mark scheme
2(a)
Python TheArray = [] TheArray = random.sample(range(0,101),20)
2(b) [3 marks]
1 mark each • Procedure header (and close) taking (array) as parameter • Outputting array contents once … • … on one line with a space between each integer Example program code Java public static void PrintArray(Integer[] DataArray){ String Output = ""; for(Integer X = 0; X < 20; X++){ Output += Integer.toString(DataArray[X]) + " "; } System.out.println(Output); } VB.NET Sub PrintArray(DataArray() As Integer) Dim Output As String = "" For X = 0 To 19 Output = Output + Str(DataArray(X)) + " " Next X Console.WriteLine(Output) End Sub Python def PrintArray(DataArray): Output = "" for Item in DataArray: Output = Output + str(Item) + " " print(Output)
2(c)
VB.NET Function BubbleSort(DataArray() As Integer) Dim Swap As Boolean = True Dim Temp As Integer While Swap = True Swap = False For X = 0 To DataArray.Length - 2 If DataArray(X) > DataArray(X + 1) Then Temp = DataArray(X) DataArray(X) = DataArray(X + 1) DataArray(X + 1) = Temp Swap = True End If Next X End While Return DataArray End Function Python def BubbleSort(DataArray): Swap = True while Swap == True: Swap = False for y in range(0, len(DataArray)-1): if DataArray[y] > DataArray[y+1]: DataArray[y], DataArray[y+1] = DataArray[y+1], DataArray[y] Swap = True return DataArray
2(d)(i) [3 marks]
1 mark each • Calling with array as argument PrintArray() • Calling with array as argument and storing/using return value BubbleSort() • Outputting and calling with (returned) array as argument "Sorted" PrintArray() Example program code Java PrintArray(TheArray); Integer[] SortedArray = new Integer[20]; SortedArray = BubbleSort(TheArray); System.out.println("Sorted"); PrintArray(SortedArray); VB.NET PrintArray(TheArray) Dim SortedArray(19) As Integer SortedArray = BubbleSort(TheArray) Console.WriteLine("Sorted") PrintArray(SortedArray) Python PrintArray(TheArray) SortedArray = BubbleSort(TheArray) print("Sorted") PrintArray(SortedArray)
2(d)(ii) [1 mark]
1 mark • Output shows unsorted array of 20 integers between 0 and 100 inclusive before sorting, “Sorted” output, array of the same integers sorting into ascending order. All screenshots will be unique to the candidate
2(e)
VB.NET Function RecursiveBinarySearch(DataArray() As Integer, Lower As Integer, Upper As Integer, DataToFind As Integer) Dim Middle As Integer If Upper >= Lower Then Middle = Lower + (Upper - Lower) \ 2 If DataArray(Middle) = DataToFind Then Return Middle ElseIf DataArray(Middle) > DataToFind Then Return RecursiveBinarySearch(DataArray, Lower, Middle - 1, DataToFind) Else Return RecursiveBinarySearch(DataArray, Middle + 1, Upper, DataToFind) End If Else Return -1 End If End Function Python def RecursiveBinarySearch(DataArray, Lower, Upper, DataToFind): if Upper >= Lower: Middle = Lower + (Upper - Lower) // 2 if DataArray[Middle] == DataToFind: return Middle elif DataArray[Middle] > DataToFind: return RecursiveBinarySearch(DataArray, Lower, Middle - 1, DataToFind) else: return RecursiveBinarySearch(DataArray, Middle + 1, Upper, DataToFind) else: return -1
2(f)(i) [3 marks]
1 mark each • Prompt and input of integer • Call of RecursiveBinarySearch(SortedArray, 0, 19, input) • Output of if returned and output "Not found" –1 "Found at position" Example program code Java System.out.println("Enter the number to find"); Scanner scanner = new Scanner(System.in); Integer DataToFind = Integer.parseInt(scanner.nextLine()); Integer Location = RecursiveBinarySearch(SortedArray, 0, 19, DataToFind); if(Location == -1){ System.out.println("Not found"); }else{ System.out.println("Found at position " + Location); } VB.NET Console.WriteLine("Enter the number to find ") Dim DataToFind As Integer = Console.ReadLine() Dim Location As Integer = RecursiveBinarySearch(SortedArray, 0, 19, DataToFind) If Location = -1 Then Console.WriteLine("Not found") Else Console.WriteLine("Found at position " & Location) End If Python DataToFind = int(input("Enter the number to find ")) Location = RecursiveBinarySearch(SortedArray, 0, 19, DataToFind) if Location == -1: print("Not found") else: print("Found at position", Location)
2(f)(ii) [2 marks]
1 mark each • screenshot showing smallest number in array input and found message with index 0 number in array input and found message with index 19 • screenshot showing a number not in the array input and an output of "Not found" All screenshots will be unique to the candidate
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 is being developed to implement a customer loyalty scheme for a coffee shop.
The programmer has decided that the following data items need to be stored for each customer:
| Data item | Description |
|---|---|
| customer ID | a unique six-digit string |
| points | an integer value that is increased by one for every cup of coffee the customer orders |
When a customer visits the shop and orders coffee, the scheme operates as follows:
The total number of points is increased by the number of coffees ordered.
If just one cup of coffee is ordered and the number of points goes above 10, then:
the cup of coffee they have just ordered is given to them free of charge
the number of points is reduced by 11.
- If the order is for multiple coffees and the number of points goes above 10, then:
they get one coffee free of charge for every 11 points
the number of points is reduced by 11 for each free coffee.
For example, the:
customer currently has 9 points
customer orders 16 cups of coffee
total number of points now becomes 25
customer gets 2 free coffees and now has 3 points left.
The programmer has defined a program module that is called every time a customer places an order:
| Module | Description |
|---|---|
| CustomerOrder() | • called with two integer parameters: ◦ the number of coffees ordered ◦ the current number of points • output a suitable message giving the number of free coffees • return a value for the new points total. |
(a) Write pseudocode for module CustomerOrder() 6 marks
(b) A text file Loyalty.txt will be used to store the data items for the loyalty scheme. The data items for each customer will be stored on a separate line of the text file where each data item is separated by a comma:
<CustomerID>,<Points>
The contents of the text file Loyalty.txt will always be stored in ascending order by customer ID.
When the data items are read from or written to the text file Loyalty.txt, they may need to be converted to the appropriate data type.
Each customer has a unique customer ID starting at "100001" with this value increasing by one each time a new customer joins the loyalty scheme.
When a customer joins the loyalty scheme, they are assigned the next customer ID and value of points is set to 0.
For example, if the loyalty scheme has 204 customers and a new customer joins the loyalty scheme, the following line is added to the text file Loyalty.txt:
"100205,0"
You can assume that the number of customers in the loyalty scheme will never be more than 9000. The programmer has defined a program module as follows:
| Module | Description |
|---|---|
| AddNewCustomers() | • called with an integer parameter representing the number of new customers to be added to the loyalty scheme • adds a new line, containing the required information, to the text file Loyalty.txt for each customer added to the loyalty scheme • outputs each new customer ID added to the loyalty scheme |
(i) Write pseudocode for module AddNewCustomers() 8 marks
Assume that there is at least one customer already in the loyalty scheme.
(ii) The requirements for AddNewCustomers() are changed. There may be no existing customers in the loyalty scheme. 4 marks
Explain the changes that will need to be made to the module AddNewCustomers()
Show mark scheme
7(a) [6 marks]
INTEGER Points + Number 0 NumberFree + 1 NewPoints -11 Number - 1 Function header and ending and parameters and return type Number of coffees ordered added to points Correct calculation of one free coffee Attempted calculation of multiple free coffees and reduced NewPoints Output number of free drinks with suitable message Return of NewPoints
7(b)(i) [8 marks]
STR_TO_NUM((LEFT(Line, 6)) 1 TO NumToAdd CustomerID + 1 NUM_TO_STR(CustomerID) & ",0" All variables used are declared using the correct type including a string and an integer Open file in read mode and close (before opening in append mode) Conditional loop with EOF("Loyalty.txt") Read from file // Count number of records in the file Line Open the file in append mode and subsequently close Extract from and convert to integer // use count from CustomerID Line MP4 to generate last stored CustomerID A (count controlled) loop for the number of customers to add Increment and output the new in loop CustomerID CustomerID Create string for new and write to file in loop CustomerID Check if the text file exists / is empty
7(b)(ii) [4 marks]
loyalty.txt If file does not exist it must be created (using write mode) If the file has to be created / is empty then set the first to CustomerID 100001 Write to (using write mode) "100001,0" loyalty.txt For all but the first customer (to be added to the empty file) use the existing code / module
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
An algorithm will:
input 100 integer values, one value at a time
store the first value input into the first location of the array Number
store the next input value in the next unused location of the array Number
output the contents of Number array in the opposite sequence to that in which the values were input.
Complete the program flowchart to represent the algorithm.
Variable declarations are not required.
START
END 6 marks
Show mark scheme
4 [6 marks]
One mark for each functional group as listed:
- Initialise Index used for to either 1 or 0 before first loop Number
- Loop 100 times
- Input value
- Increment array index and store value in array at element Number referenced by array in a loop index
- Output loop starts at last element in array Number
- Output array element referenced by in a loop Number Index
- Output all elements of array once in reverse order Number Max 6
Two arrays Data and Pointer are accessed by the procedure Place()
Data and Pointer are both global arrays of type INTEGER
The contents of these two arrays are shown:
Data Pointer
1 1018 1 7
2 1007 2 3
3 1010 3 1
4 1056 4 6
5 1092 5 -1
6 1062 6 5
7 1034 7 4
8 0 8 9
9 0 9 10
10 0 10 -1
Study the pseudocode:
PROCEDURE Place(Value : INTEGER, Start : INTEGER, Unused : INTEGER) DECLARE New, Current, Last : INTEGER CONSTANT NullPointer = -1 New Unused Last NullPointer Current Start WHILE Current <> NullPointer AND Data[Current] < Value Last Current Current Pointer[Current] ENDWHILE Pointer[New] Pointer[Last] Pointer[Last] New Data[New] Value ENDPROCEDURE
(a) (i) Complete the trace table below by dry running the procedure Place() when it is called by the statement: 4 marks
CALL Place(1043, 2, 8)
| Value | Start | Unused | New | Last | Current |
|---|---|---|---|---|---|
(ii) Complete the diagram showing the contents of the global arrays Data and Pointer after the procedure Place() has run to completion when called as shown in part (a)(i). 3 marks
Data Pointer
1 1018 1
2 1007 2
3 1010 3
4 1056 4
5 1092 5
6 1062 6
7 1034 7
8 8
9 9
10 10
(b) The operation carried out by procedure Place() together with the arrays form part of the implementation of an Abstract Data Type (ADT). 2 marks
Identify the ADT and state the operation carried out by procedure Place()
Show mark scheme
6(a)(i) [4 marks]
Value Start Unused New Last Current 1043 2 8 8 –1 2 Region 1 2 3 Region 2 3 1 Region 3 1 7 7 4 Region 4 Award 1 mark per region
6(a)(ii) [3 marks]
Data Pointer 1018 7 1 1 1007 3 2 2 1010 1 3 3 1056 6 4 4 1092 –1 5 5 1062 5 6 6 1034 8 7 7 1043 4 8 8 0 10 9 9 0 –1 10 10 Mark as follows: 1 mark for global array row 8 containing the value 1043 Data 1 mark for global array row 7 containing the value 8 and row 8 Pointer containing the value 4 1 mark for all other rows in both arrays
6(b) [2 marks]
Example answer: The ADT is a linked list and the procedure inserts / add a new node / Place() value into it / the linked list Mark as follows:
- 1 mark for identifying the ADT as a linked list
- 1 mark for identifying operation as inserting / adding a value / node into a linked list
A program is being developed to implement a customer loyalty scheme for a coffee shop.
Each customer has a unique customer ID starting at 10001 with this value increasing by one each time a new customer joins the loyalty scheme.
For example, the third customer who joins the loyalty scheme is given the customer ID 10003
The loyalty scheme is limited to 1000 customers.
A customer is awarded a loyalty point every time they buy a coffee.
The programmer has decided to use a global 2D array Loyalty of type INTEGER. The array Loyalty is made up of 1000 rows and 2 columns. Each row relates to one customer; column 1 contains the unique customer ID and column 2 contains the number of customer loyalty points.
Rows in the array Loyalty that are not currently being used have the value of Column 1 set to 99999
The array is sorted in ascending order by customer ID.
The programmer has defined a program module:
| Module | Description |
|---|---|
| FindCustomer() | • called with parameter of type INTEGER representing a customer ID • searches the Loyalty array for this customer ID • the search will stop as soon as the customer ID is found • the search should efficiently deal with the situation when the customer ID is not stored in the Loyalty array • if the customer ID is found, return an integer value representing the loyalty points, otherwise return -1 |
(a) Write efficient pseudocode for module FindCustomer() 8 marks
(b) A customer can claim a free coffee for every 11 loyalty points. 7 marks
The programmer has defined a second program module:
| Module | Description |
|---|---|
| PointsReport() | • output the customer ID for each customer who has 11 or more loyalty points • output the average loyalty points for all customers in the Loyalty array along with an appropriate message |
Write efficient pseudocode for module PointsReport()
Assume the array contains the data for at least one customer.
(c) The programmer decides to amend the customer ID; it will be stored as a STRING instead of an INTEGER. This means that the 2D array Loyalty can no longer be used.
(i) Explain why the 2D array Loyalty can no longer be used. 1 mark
(ii) Explain how a 1D array could be used to store both the loyalty points and the amended customer ID. 2 marks
Show mark scheme
7(a)
Mark points
- Create function header and ending with correct parameter and return type
- Check is within range and if not return –1 CustomerID
- Conditional loop that halves array search space with each iteration
- Check if is stored in current array element in loop CustomerID
- Mechanism to end loop if is found in array in a loop CustomerID
- Mechanism to end loop if is not in array in a loop CustomerID
- If found in array then return correct loyalty points CustomerID
- If not in array then return –1 CustomerID
7(b) [7 marks]
Example solution PROCEDURE PointsReport() DECLARE Count : INTEGER DECLARE Index : INTEGER DECLARE Sum : INTEGER DECLARE Average : REAL Index 1 Count 0 Sum 0 WHILE Loyalty[Index, 1] <> 99999 AND Index <= 1000 IF Loyalty[Index, 2] >= 11 THEN OUTPUT Loyalty[Index, 1] ENDIF Count Count + 1 Sum Sum + Loyalty[Index, 2] Index Index + 1 ENDWHILE Average Sum / Count OUTPUT "The average points of all the customers is ", Average ENDPROCEDURE Mark as follows:
- Create procedure header and ending
- Declare and initialise , and Index Sum Count
- Loop through all elements in array Loyalty
- … or terminates when column1 of array equals in a loop Loyalty 99999
- Check if loyalty points greater than or equal to in a loop 11
- If true output customer ID 7 Sum points and Increment in a loop Count 8 Calculate and output average with an appropriate message Max 7
7(c)(i) [1 mark]
An array can only store data of the same type // An array cannot store data of different types
7(c)(ii) [2 marks]
1 mark for each point
- a new (composite) data type / record is defined (that consists of both and ) INTEGER STRING
- an array based on this new type is declared Alternative 1 mark for each point
- Converting loyalty points to string and concatenating / joining / append with Customer ID
- Storing concatenated string in an array of string
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 programmer is developing a new stock control program for a shop owner to produce sales reports.
(a) A text file Sales.txt stores strings representing the number of items sold. 5 marks
The file contains 52 lines, each representing the number of items sold in each week of the year.
For example:
File line number File data 1 "350" 2 "502" 3 "434"
49 "492" 50 "872" 51 "772" 52 "201"
The example shows that 502 items were sold in week 2.
The owner requires a module to output all week numbers where the number of items sold is greater than 500.
Describe an algorithm that produces the required module.
Do not include pseudocode statements in your answer.
(b) Once the program has been completed, it is tested using the walkthrough method. 3 marks
Describe the walkthrough method and explain how it can be used to identify errors.
Show mark scheme
4 Sales.txt MP2 Read a line (from the text file)
MP3 Convert the line read (string) to a number MP4 If the number is greater than 500 and then output week number MP5 Increment week number (must have been Initialised … ) MP6 Repeat from step 2 for 52 times // Repeat from step 2 until end of file Max 5
4(b) [3 marks]
MP1 Going through the program a line / statement at a time // doing a dry run // single-stepping ( at run-time with an IDE) // Peer testing/review is carried out MP2 Creating a trace table MP3 Draw up test data // draw up list of inputs with expected output // boundary, normal, abnormal data is used MP4 Errors will be indicated when a variable / output gives an unexpected value MP5 Faults in the logic of the program can be detected // Errors may be indicated by an unexpected path through the program Max 3
A module Parity() takes a string as a parameter. The parameter has the identifier BitString and it represents a binary value.
The module will concatenate a single character to the end of BitString by applying one of the two rules:
'0' if Bitstring contains an even number of 1s
'1' if Bitstring contains an odd number of 1s.
The modified value of BitString is then returned.
For example:
| Parameter | String returned | Explanation |
|---|---|---|
| "0010010110" | "00100101100" | there are an even number of 1s in the string passed to Parity() so a '0' is concatenated to the end of BitString |
| "101010" | "1010101" | there are an odd number of 1s in the string passed to Parity() so a '1' is concatenated to the end of BitString |
Write pseudocode for the module Parity()
Assume the parameter BitString can only contain the characters '0' and '1' 8 marks
Show mark scheme
5 [8 marks]
Example solution: FUNCTION Parity(BitString : STRING) RETURNS STRING DECLARE Index, Count: INTEGER Count 0 FOR Index 1 TO LENGTH(BitString) IF MID(BitString, Index, 1) = '1' THEN Count Count + 1 ENDIF NEXT Index IF Count MOD 2 = 1 THEN BitString BitString & '1' ELSE BitString BitString & '0' ENDIF RETURN BitString ENDFUNCTION MP1 Function heading and ending and parameter ( ) and return STRING type STRING MP2 Loop for length of BitString MP3 Extract current character in a loop MP4 Compare current character to or in a loop '1' '0' MP5 Increment count and was Initialised earlier in a loop MP6 Check if even/odd number of 1s MP7 Append or as appropriate '1' '0' MP8 Return amended BitString
A program sorts the data in the 1D array DataArray and searches DataArray for specific
values.
DataArray stores 14 integer values and is declared local to the main program.
(a) Write program code to create DataArray and initialise it with the following data values in the order they are written: 1 mark
0 3 4 56 67 44 43 32 31 345 45 6 54 1
Save your program as Question2_J25 .
Copy and paste the program code into part 2(a) in the evidence document.
(b) The function InsertionSort() takes an array of integers as a parameter. The function sorts the data in the array into ascending numerical order using an insertion sort. The function returns the sorted array. 5 marks
Write program code for InsertionSort()
You must not use any inbuilt sorting functions for your programming language.
Save your program.
Copy and paste the program code into part 2(b) in the evidence document.
(c) The procedure OutputArray() takes an array of integers as a parameter. The procedure outputs each element in the array from the first element to the last element. The output is on one line with a space between each number. 2 marks
An example output is:
"0 3 4 56 67 44 43 32 31 345 45 6 54 1"
Write program code for OutputArray()
Save your program.
Copy and paste the program code into part 2(c) in the evidence document. (d) (i) The main program needs extending to: 2 marks
output the content of the unsorted array using
OutputArray()sort the array using
InsertionSort()output the content of the sorted array using
OutputArray()
Write program code to extend the main program.
Save your program.
Copy and paste the program code into part 2(d)(i) in the evidence document.
(ii) Test your program. 1 mark
Take a screenshot of the output(s).
Save your program.
Copy and paste the screenshot into part 2(d)(ii) in the evidence document.
(e) The function Search() performs a binary search to find ItemToFind in DataArray The function takes two parameters: 6 marks
DataArray, an array of integersItemToFind, an integer to find inDataArray
The function returns:
the index of
ItemToFindif it is inDataArray–1ifItemToFindis not inDataArray
Write program code for Search()
You must not use any inbuilt searching functions for your programming language.
Save your program.
Copy and paste the program code into part 2(e) in the evidence document.
(f) (i) The main program needs extending to call Search() with the sorted array four times: 2 marks
the first time to find the index of the integer 0
the second time to find the index of the integer 345
the third time to find the index of the integer 67
the fourth time to find the index of the integer 2
If the integer is found in the array, output an appropriate message that includes the index. If the integer is not found, output that it was not found.
Write program code to extend the main program.
Save your program.
Copy and paste the program code into part 2(f)(i) in the evidence document.
(ii) Test your program. 1 mark
Take a screenshot of the output(s).
Save your program.
Copy and paste the screenshot into part 2(f)(ii) in the evidence document.
Show mark scheme
2(a) [1 mark]
1 mark for array declared with data values: 0 3 4 56 67 44 43 32 31 345 45 6 54 1
2(b) [5 marks]
1 mark each • header (and close) taking array as a parameter and returning (attempt at) sorted array InsertionSort() • Looping through/for each element • Extracting element and comparing to sorted list … • … moving elements in sorted list • … and inserting element in correct position (ascending order)
Return DataArray CurrentValue = DataArray(X) Y = X - 1 While Y >= 0 AndAlso CurrentValue < DataArray(Y) DataArray(Y + 1) = DataArray(Y) Y = Y - 1 End While DataArray(Y + 1) = CurrentValue
2(c) [2 marks]
1 mark each • header (and close) taking an array parameter and outputting the array contents … OutputArray() • … in correct format
If DataArray(X) <> -1 Then Output = Output & DataArray(X) & " " End If X = X + 1
2(d)(i) [2 marks]
1 mark each • Calling with array parameter and storing/using return array InsertionSort() • … calling with array parameter before and after OutputArray() InsertionSort()
2(d)(ii) [1 mark]
1 mark for output showing unsorted then sorted array e.g.
2(e) [6 marks]
1 mark each • header (and close) taking array and integer as parameters Search() • Looping/recursive calls until no elements left/Low<=High and returning –1 if not found • … calculating middle index and accessing this value • … comparison of array at middle value to integer parameter • … if they are equal return mid • … if array[mid] < parameter update low to middle + 1, if array[mid] > parameter update high to middle – 1 // recursive call with updated low and updated high
Middle = (High + Low) \ 2 If DataArray(Middle) < ItemToFind Then Low = Middle + 1 ElseIf DataArray(Middle) > ItemToFind Then High = Middle - 1 Else Return Middle End If
2(f)(i) [2 marks]
1 mark each • Calling with all four sets of values 0 345 67 2 Search() • … outputting 'not found' or index in appropriate message each time
2(f)(ii) [1 mark]
1 mark for output showing locations for first 3 and not found for 4th
An algorithm will output the last three lines from a text file Result.txt
The lines need to be output in the same order as they appear in the file.
Assume:
Three variables LineX, LineY and LineZ will store the three lines. These are of type string and all three variables have been initialised to an empty string.
The file exists and contains at least three lines.
(a) The algorithm to output the lines is expressed in eight steps. 4 marks
Complete the steps.
Open the file
Loop until
______ and store in ThisLine
Assign LineY to LineX
Assign LineZ to LineY
Assign ThisLine to LineZ
After the loop,
Output LineX, LineY, LineZ
(b) Explain the purpose of steps 4, 5 and 6 in the algorithm from part (a). 1 mark
Show mark scheme
3(a) [4 marks]
One mark per emboldened part: 1 Open the file (Result.txt) in read mode 2 Loop until EOF(Result.txt) // EOF // end of file 3 Read a / the / next line (from the file) and store in ThisLine 4 Assign to LineY LineX 5 Assign to LineZ LineY 6 Assign to ThisLine LineZ 7 After the loop, close the file (Result.txt) 8 Output , , LineX LineY LineZ
3(b) [1 mark]
Example answer: So that the last three lines of the file are output in the correct order A mark for mentioning one of: • (Ensuring) the lines are output in correct order • Ordering the last three lines • Ordering the lines so they are in the same order as (they occur) in the file Max 1 marks
3(c) [4 marks]
Two loop solution
One mark per point:
1
Loop until given line number (-1) /
(lines have been
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 program uses a stack to hold up to 60 numeric values. The stack is implemented using two integer variables and a 1D array.
The array is declared in pseudocode as shown:
DECLARE ThisStack : ARRAY[1:60] OF REAL
The stack operates as follows:
Global variable SP acts as a stack pointer that points to the next available stack location. The value of SP represents an array index.
Global variable OnStack represents the number of values currently on the stack.
The stack grows upwards from array element index 1.
(a) (i) Give the initial values that should be assigned to the two variables. 1 mark
SP
OnStack
(ii) Explain why it is not necessary to initialise the array elements before the stack is used. 2 marks
(b) A function to add a value to ThisStack is expressed in pseudocode as shown. 4 marks
The function will return a value to indicate whether the operation was successful or not.
Complete the pseudocode by filling in the gaps.
FUNCTION Push(ThisValue : REAL) RETURNS BOOLEAN
DECLARE ReturnValue : BOOLEAN
IF ______ THEN
RETURN ______ // stack is already full
ENDIF
______ ThisValue
SP
OnStack OnStack + 1
RETURN TRUE
ENDFUNCTION
Show mark scheme
3(a)(i) [1 mark]
: 1 SP : 0 OnStack One mark for both correct values
3(a)(ii) [2 marks]
MP1 Unused values cannot be popped / taken off the stack // initialised values would never be used / unused elements cannot be accessed MP2 ... until a value has first been pushed / written // overwrites previous value
3(b) [4 marks]
Example solution: FUNCTION Push(ThisValue : REAL) RETURNS BOOLEAN DECLARE ReturnValue : BOOLEAN IF OnStack = 60 / >59 // SP = 61 / SP > 60 // outside the range 1 to 60 SP THEN RETURN FALSE // Stack is already full ENDIF ThisStack[SP] ThisValue SP SP + 1 OnStack OnStack + 1 RETURN TRUE ENDFUNCTION1 Mark as follows: One mark per gap
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 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 program is being developed to implement a game for up to six players.
During the game, each player assembles a team of characters. At the start of the game there are 45 characters available.
Each character has four attributes, as follows:
| Attribute | Examples | Comment |
|---|---|---|
| Player | 0, 1, 3 | The player the character is assigned to. |
| Role | Builder, Teacher, Doctor | The job that the character will perform in the game. |
| Name | Bill, Lee, Farah, Mo | The name of the character. Several characters may perform the same role, but they will each have a unique name. |
| Level | 14, 23, 76 | The skill level of the character. An integer in the range 0 to 100 inclusive. |
The programmer has defined a record type to define each character.
The record type definition is shown in pseudocode as follows:
TYPE CharacterType DECLARE Player : INTEGER DECLARE Role : STRING DECLARE Name : STRING DECLARE Level : INTEGER ENDTYPE
The Player field indicates the player to which the character is assigned (1 to 6). The field value is 0 if the character is not assigned to any player.
The programmer has defined a global array to store the character data as follows:
DECLARE Character : ARRAY[1:45] OF CharacterType
At the start of the game all record fields are initialised, and all Player field values are set to 0
The programmer has defined a program module as follows:
| Module | Description |
|---|---|
| Assign() | • called with two parameters: ○ an integer representing a player ○ a string representing a character role • search the Character array for an unassigned character with the required role • If found, assign the character to the given player and output a confirmation message, for example: "Bill the Builder has been assigned to player 3" • If no unassigned character with the required role is found, output a suitable message. |
(a) Write pseudocode for module Assign(). 7 marks
(b) A new module will store the contents of the Character array in a text file. 7 marks
The module is defined as follows:
| Module | Description |
|---|---|
| Save() | • form a string from each record with fields separated by the character '^' • write each string to a separate line of the new file named SaveFile.txt |
Complete the pseudocode for module Save().
PROCEDURE Save()
ENDPROCEDURE
(c) The program is changed and the record type definition is modified as follows: 2 marks
TYPE CharacterType DECLARE Player : INTEGER DECLARE Role : STRING DECLARE Name : STRING DECLARE Level : INTEGER DECLARE Status : BOOLEAN ENDTYPE
Describe how the additional Boolean field may be stored with the rest of the fields on one line of a text file.
(d) The save operation is to be extended so that multiple files may be saved as the game progresses. This will allow the user to restore the game from any saved position. The filename must reflect the sequence in which the files are saved. 2 marks
Describe a method that would allow multiple files to be saved and give an example of two consecutive filenames.
Method
Example
Show mark scheme
8(a) [7 marks]
Example solution: PROCEDURE Assign(ThisRole : STRING, ThisPlayer : INTEGER) DECLARE Index : INTEGER DECLARE Done : BOOLEAN Done FALSE Index 1 WHILE Index < 46 AND Done = FALSE IF Character[Index].Player = 0 AND __ Character[Index].Role = ThisRole THEN Character[Index].Player ThisPlayer Done TRUE ELSE Index Index + 1 ENDIF ENDWHILE IF Done = TRUE THEN OUTPUT Character[Index].Name, the ,__ " " Character[Index].Role, __ has been assigned to player , ThisPlayer " " ELSE OUTPUT No characters with this role are available " " ENDIF ENDPROCEDURE Mark as follows: MP1 Loop until ‘found’ or all 45 elements considered MP2 Test of field – i.e. not value in a loop Player MP3 ... – i.e. match for parameter in a loop AND Role ThisRole MP4 If available character found, assign to the character in a ThisPlayer loop MP5 When character found set termination condition/flag MP6 Both OUTPUT messages logically correctly placed MP7 Both OUTPUT statements correctly formed
8(b) [7 marks]
Example solution: PROCEDURE Save() DECLARE Index : INTEGER DECLARE Line : STRING CONSTANT SEP = '^' OPENFILE SaveFile.txt FOR WRITE " " FOR Index 1 TO 45 Line NUM_TO_STR(Character[Index].Player) & SEP Line Line & Character[Index].Role & SEP Line Line & Character[Index].Name & SEP Line Line & NUM_TO_STR(Character[Index].Level) WRITEFILE SaveFile.txt , Line " " NEXT Index CLOSEFILE SaveFile.txt " " ENDPROCEDURE Mark as follows: MP1 Declaration of local integer for ( and string type for Index Line) MP2 Open in write mode and subsequently close "SaveFile.txt" MP3 Loop through 45 elements MP4 Attempt to form
- four fields
in a loop
Line
MP5
Correct use of
in a loop
NUM_TO_STR()x2 (Player and Level)
MP6
Correct use of
three
&
& in a loop strings MP7 Line from MP4 written to file in a loop
8(c) [2 marks]
MP1 Encode as a character / string Status MP2 Append the ‘^’ separator and the character/string
8(d) [2 marks]
MP1 Method: Create a filename suffix which is incremented for each file save MP2 Example: SaveFile01.txt, SaveFile02.txt
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
A program is being developed to implement a game for up to six players.
During the game, each player assembles a team of characters. At the start of the game there are 45 characters available.
Each character has four attributes, as follows:
| Attribute | Examples | Comment |
|---|---|---|
| Player | 0, 1, 3 | The player the character is assigned to. |
| Role | Builder, Teacher, Doctor | The job that the character will perform in the game. |
| Name | Bill, Lee, Farah, Mo | The name of the character. Several characters may perform the same role, but they will each have a unique name. |
| Skill level | 14, 23, 76 | An integer in the range 0 to 100, inclusive. |
The programmer has defined a record type to define each character. The record type definition is shown in pseudocode as follows:
TYPE CharacterType DECLARE Player : INTEGER DECLARE Role : STRING DECLARE Name : STRING DECLARE SkillLevel : INTEGER ENDTYPE
The Player field indicates the player to which the character is assigned (1 to 6). This field value is 0 if the character is not assigned to any player.
The programmer has defined a global array to store the character data, as follows:
DECLARE Character : ARRAY[1:45] OF CharacterType
At the start of the game all record fields are initialised, and all Player fields are set to 0
The programmer has defined a program module as follows:
| Module | Description |
|---|---|
| Count() | • called with two parameters: ○ an integer representing a player ○ a string representing a character role • searches the Character array for characters with the given role that are assigned to the given player • counts the number of assigned characters and sums their total skill level • outputs the result of the search if characters with the given role are found, for example: "Player 3 has 4 characters with the role of Teacher and the total skill level is 65" • if no characters with the given role are found, outputs: "No characters with that role are assigned to this player" |
(a) Complete the pseudocode for module Count(). 7 marks
PROCEDURE Count(ThisPlayer : INTEGER, ThisRole : STRING)
ENDPROCEDURE
(b) The Character array data has been saved in the text file SaveFile.txt Each line of the file contains one element of the array (one record). 7 marks
New modules are defined:
| Module | Description |
|---|---|
| Extract() (already written) |
• called with two parameters: ○ a string representing a complete line from the text file ○ an integer representing a field number (see structure below) • returns a string representing the required field |
| Restore() | • opens the text file SaveFile.txt • reads lines from the file and assigns values to each record in the Character array using data from each line of the file |
As a reminder, the record structure is repeated here:
TYPE CharacterType DECLARE Player : INTEGER //Field number 1 DECLARE Role : STRING //Field number 2 DECLARE Name : STRING //Field number 3 DECLARE SkillLevel : INTEGER //Field number 4 ENDTYPE
Write pseudocode for module Restore().
You must use the module Extract().
(c) The game can last for several days and users often find that they have to close and rerun the game program many times in order to complete it. 2 marks
Describe the benefit of using the file SaveFile.txt as described in part (b).
Show mark scheme
8(a) [7 marks]
Example solution PROCEDURE Count(ThisPlayer : INTEGER, ThisRole : STRING) DECLARE Index, Num, Total : INTEGER Num 0 Total 0 FOR Index 1 TO 45 IF Character[Index].Player = ThisPlayer AND __ Character[Index].Role = ThisRole THEN Num Num + 1 Total Total + Character[Index].SkillLevel NEXT Index IF Num > 0 THEN OUTPUT "Player ", ThisPlayer, __ " has ", Num, " characters with the role of ", ThisRole, " and the total skill level is ", Total ELSE OUTPUT "No characters with that role are assigned to this player" ENDIF ENDPROCEDURE MP1 Initialisation of local integers for and Num Total MP2 Loop through 45 elements MP3 Attempt to check Player and Role fields in a loop MP4 Correctly compare field with parameter in a loop Player MP5 Correctly compare field with parameter in a loop Role MP6 ... if player and role found, increment and sum Skill Total in a Num loop MP7 Test for any matches after the loop MP8 Both possible OUTPUT statements correctly formed following an attempt at MP6 but outputting one only Max 7 marks
8(b) [7 marks]
Example solution: PROCEDURE Restore() DECLARE Index : INTEGER DECLARE Line : STRING OPENFILE "SaveFile.txt" FOR READ FOR Index 1 TO 45 READFILE "SaveFile.txt", Line Character[Index].Player STR_TO_NUM(Extract(Line, 1)) Character[Index].Role Extract(Line, 2) Character[Index].Name Extract(Line, 3) Character[Index].Skill STR_TO_NUM(Extract(Line, 4)) NEXT Index CLOSEFILE "SaveFile.txt" ENDPROCEDURE Mark as follows: MP1 Open the file in read mode and subsequently close MP2 Loop through 45 elements MP3 Read a line from the file in a loop MP4 Attempt to use in a loop Extract() MP5 Correct use of for all fields in a loop Extract() MP6 Use of on Player and Skill in a loop STR_TO_NUM() MP7 Completely correct extraction and assignment of all fields in a loop
8(c) [2 marks]
MP1 The array / character data can be saved before the Character program is closed MP2 Allowing the game to continue using the same data / from the point it was saved
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 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()
Show mark scheme
2(a) [5 marks]
Max 5 marks MP1 Set total to zero MP2 Input a number MP3 Check if number greater than 29 and less than 71 MP4 … if check is true - add number to total MP5 Repeat from step 2 99 times // for a total of 100 iterations MP6 Output the total
2(b) [2 marks]
MP1 An iterative construct // a (count-controlled) loop MP2 A selection construct // an IF statement
Show mark scheme
2(a) [5 marks]
MP1 Initialise to first value in and to 1 Min Data MinIndex MP2 Loop through 29 more values (or 30 values in total) MP3 Compare element from with Data[] Min MP4 Set new AND save when element value < in a loop Min MinIndex Min MP5 Output MinIndex
2(b) [2 marks]
MP1 Simplifies the algorithm // easier to write / understand / test / debug MP2 It is possible to iterate through the values // can use a loop // allows the storage of many values using a single identifier
2(c) [2 marks]
One mark per underlined section DECLARE Data : ARRAY[1:120] OF REAL
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]
Show mark scheme
2(a)
One mark per point: 1 Both prompts 2 Both inputs using correct identifiers as given in question, and MyChar MyCount 3 Initialise to empty string and subsequent output after loop MyString 4 Loop iterations including decrement MyCount MyCount 5 Use of Concatenate or equivalent pseudocode statement inside loop Max 4 Marks
2(b) [4 marks]
One mark for declaration: DECLARE StartDate : DATE One mark for each underlined part of assignment: StartDate SETDATE (15, 11, 2005)
A computer shop assembles computers using items bought from several suppliers. A text file
Stock.txt contains information about each item.
Information for each item is stored as a single line in the Stock.txt file in the format:
<ItemNum><SupplierCode><Description>
||s follows:||
|---|---|---|
||**Format**|**Comment**|
|`ItemNum`|4 numeric characters|unique for each item in the range<br>"0001" to "5999" inclusive|
|`SupplierCode`|5 alphabetic characters|to identify the supplier of the item|
|`Description`|a string|a minimum of 12 characters|
The file is organised in ascending order of ItemNum and does not contain all possible values in
the range.
| A programmer has | started to define program modules as follows: |
|---|---|
| Module | Description |
SuppExists()(already written) |
• called with a parameter of type string representing a supplier code • returns TRUE if the supplier code is already in use, otherwise returnsFALSE |
IsNewSupp() |
• called with a parameter of type string representing a new supplier code • returns TRUE if the string only contains alphabetic characters (eitherupper or lower case) and the supplier code isnot already in use, otherwise returns FALSE |
(a) Write pseudocode for module IsNewSupp() . 7 marks
Module SuppExists() has already been written and should be used as part of your solution.
Module SuppExists() will generate a run-time error if the given parameter is not
5 characters in length.
(b) A new module has been defined: 7 marks
| Module | Description |
|---|---|
CheckNewItem() |
• called with a parameter of type string representing a line of item information • checks to see whether an item with the same ItemNum alreadyexists in the file • returns TRUE if theItemNum is not already in the file, otherwisereturns FALSE |
Write efficient pseudocode for module CheckNewItem() .
(c) The program modules SuppExists(), IsNewSupp() and CheckNewItem() are part of a group of modules that are combined to create a complete stock control program.
Each module in the program is tested individually during development and is debugged as necessary. It is then added to the program and further testing performed.
(i) Identify this method of testing. 1 mark
(ii) One of the modules does not work properly when it is added to the program. 2 marks
Describe a testing method that can be used to address this problem so that testing can continue and other modules can be added.
(d) A new module AddItem() will be used to add information to the Stock.txt file. 1 mark
State the file mode that should be used for the algorithm within this module.
(e) A new module FindItem() searches for a given item in the Stock.txt file, which is already organised in ascending order of ItemNum . 3 marks
Describe how this organisation may improve the efficiency of the algorithm.
Show mark scheme
8(a) [7 marks]
DECLARE Index : INTEGER DECLARE ThisChar : CHAR IF LENGTH(ThisString) <> 5 THEN RETURN FALSE // invalid SupplierCode length ENDIF IF SuppExists(ThisString) THEN RETURN FALSE // SupplierCode already exists ENDIF FOR Index 1 TO 5 ThisChar TO_LOWER(MID(ThisString, Index, 1)) IF ThisChar < 'a' OR ThisChar > 'z'THEN RETURN FALSE ENDIF NEXT Index RETURN TRUE ENDFUNCTION Mark as follows: 1 Check is exactly 5 characters in length ThisString 2 Use of with a string of 5 characters as a parameter SuppExists() 3 Loop for 5 iterations // loops for length of string parameter 4 Extract a character in a loop 5 Test if char is alphabetic in a loop 6 … catering for both upper and lower case 7 Return Boolean following a reasonable attempt FUNCTION CheckNewItem(NewLine : STRING) RETURNS BOOLEAN
8(b)
DECLARE NotFound : BOOLEAN DECLARE NewItemNum, ThisItemNum, ThisLine : STRING NotFound TRUE OPENFILE "Stock.txt" FOR READ NewItemNum LEFT(NewLine, 4) ThisItemNum "0000" //rogue initial value WHILE NOT EOF("Stock.txt") AND NotFound = TRUE AND__ ThisItemNum < NewItemNum READFILE("Stock.txt", ThisLine) //brackets optional ThisItemNum LEFT(ThisLine, 4) IF ThisItemNum = NewItemNum THEN NotFound FALSE ENDIF ENDWHILE CLOSEFILE "Stock.txt" RETURN NotFound ENDFUNCTION Mark as follows: 1 Open in READ mode and subsequently close Stock.txt 2 Extract from parameter NewItemNum 3 Conditional loop until EOF("Stock.txt") 4 ... OR found NewItemNum 5 ... OR when ThisItemNum < NewItemNum 6 Read a line from AND extract in a Stock.txt ThisItemNum loop 7 If then terminate loop / set flag in ThisItemNum = NewItemNum a loop 8 Return Boolean after reasonable attempt Max 7 marks Max 6 if function wrapper (heading and ending) missing or incorrect
8(c)(i) [1 mark]
Integration testing
8(c)(ii) [2 marks]
Two marks for the description: A dummy/simple module is written to replace the module that does not work properly The dummy/simple module will return an expected value // will output a message to show it has been called
8(d) [1 mark]
Append
8(e) [3 marks]
One mark for each part: The algorithm / search / iteration can stop /only iterates if the current value read from the file // current line in file is greater than the value being searched for
Show mark scheme
2(a) [2 marks]
MyDOB SETDATE(17, 11, 2007)
2(b) [6 marks]
NumMonths 12 - MONTH(MyDOB) One mark per underlined part
2(c) [4 marks]
One mark per array definition bullet: A (1D) array containing 7 elements of type STRING One mark per Step: Step1: Assign value "Sunday" to first element, "Monday" to second element etc. Step2: Use the function to return / find the day number from DAYINDEX() MyDoB Step3: Use the returned value as the array index / to access the element that contains the name / string Step4: Output the element / name / string Note: Max 2 for Array definition, Max 4 for steps
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) An algorithm will process data from a test taken by a group of students. The algorithm will prompt and input the name and test mark for each of the 35 students.
The algorithm will add the names of all the students with a test mark of less than 20 to an
existing text file Support_List.txt, which already contains data from other group tests.
(i) Describe the steps that the algorithm should perform. 5 marks
Do not include pseudocode statements in your answer.
Show mark scheme
2(a)(i) [5 marks]
One mark per step (or equivalent): 1 Open file in APPEND mode (and subsequent Close) 2 Prompt and Input a student name and mark 3 If mark greater than or equal to 20 jump to step 5 4 Write only the name to the file 5 Repeat from Step 2 for 35 times / the number of students
2(a)(ii) [1 mark]
Data in a file is saved after the computer is switched off / stored permanently // no need to re-enter the data when the program is re-run
2(a)(iii) [1 mark]
Example answer: So that existing file data is not overwritten.
2(b) [4 marks]
One mark per row (row 2 to 5): Input Output Next state S1 Output-X S2 Input-A Input-A (none) S2 Input-B S3 Output-W Input-A S4 Output-W
A program is being designed for a smartphone to allow users to send money to the charity of their choice.
Decomposition will be used to break the problem down into sub-problems.
Identify three program modules that could be used in the design and describe their use.
Module 1
Use
Module 2
Use
Module 3
Use 3 marks
Show mark scheme
2 [3 marks]
One mark for name and two marks for use ( Max 3 in total ): Examples include: Module: SelectCharity() Use: Allows the user to choose a particular charity Module: SpecifyAmountAndType() Use: Allows the user to specify a single or regular payment Module: MakePayment() Use: Make payment to the charity Module: ValidatePayment() Use: Validate payment details (by accessing bank computer) Module: AddBankAccountDetails() / AddPaymentDetails() Use: Allows the user to add bank account information that donation to be taken from Module: AddDonorDetails() Use: Allows user to add details such as name and contact details
(a) A programmer draws a program flowchart to show the sequence of steps required to solve a problem. 1 mark
Give the technical term for a sequence of steps that describe how to solve a problem.
(b) The table lists some of the variables used in a program.
(i) Complete the table by writing the most appropriate data type for each variable. 4 marks 2 marks
| Variable | Use of variable | Data type |
|---|---|---|
Temp |
Stores the average temperature | |
PetName |
Stores the name of my pet | |
MyDOB |
To calculate the number of days until my next birthday |
|
LightOn |
Stores state of light; light is only on or off |
(ii) One of the names used for a variable in the table in part 1(b)(i) is not an example of good practice. 4 marks
Identify the variable and give a reason why it is not good practice to use that name.
Variable
Reason
| Complete the table by evaluating each expression. | |
|---|---|
| Expression | Evaluation |
INT((31 / 3) + 1) |
|
MID(TO_UPPER("Version"), 4, 2) |
|
TRUE AND (NOT FALSE) |
|
NUM_TO_STR(27 MOD 3) |
Show mark scheme
1(a) [4 marks]
An algorithm
1(b)(i) [2 marks]
Variable Use of variable Data type Temp Stores the average temperature REAL PetName Stores the name of my pet STRING MyDOB To calculate how many days until my DATE next birthday LightOn Stores state of light; light is only on or off BOOLEAN One mark for each data type
1(b)(ii)
One mark for variable name, and one for reason Variable: Temp Reason: Name does not indicate what the variable is used for
1(c) [4 marks]
Expression Evaluation INT((31 / 3) + 1) 11 MID(TO_UPPER("Version"), 4, 2) "SI" TRUE AND (NOT FALSE) TRUE NUM_TO_STR(27 MOD 3) "0" One mark per row
Each line of a text file contains data organised into fixed-length fields as shown:
<Field 1><Field 2><Field 3>
An algorithm is required to search for the first instance of a given value of Field 2 and, if found, to output the corresponding values for Field 1 and Field 3.
Describe the algorithm needed.
Do not include pseudocode statements in your answer. 6 marks
Show mark scheme
5 [5 marks]
One mark per point to Max 6 1 Open file in read mode 2 Set up a conditional loop, repeating until the value is found or the EOF() is reached 3 Read a line from the file in a loop 4 Extract Field 2 5 Description of how Field 2 could be extracted e.g. using substring function and lengths of Field 1 and Field 2 6 Compare extracted field with search value 7 If search value found, extract Field 1and Field 3 and output them 8 Close the file after loop has finished
A string is a palindrome if it reads the same forwards as backwards.
The following strings are examples of palindromes:
"Racecar" "madam" "12344321"
Upper-case and lower-case characters need to be treated the same. For example, 'A' is equivalent to 'a'.
(a) A function IsPalindrome() will take a string parameter. The function will return TRUE if the string is a palindrome and will return FALSE if the string is not a palindrome. 7 marks
Write pseudocode for IsPalindrome() .
(b) Strings may consist of several words separated by spaces. 4 marks
For example, the string "never odd or even" becomes a palindrome if the spaces are removed.
The program flowchart represents an algorithm to produce a string OutString by removing
all spaces from a string InString .

| Set Index to 1 | |
|---|---|

Complete the table by writing the text that should replace each of the labels B, C, D, F and G .
Note: the text may be written as a pseudocode statement.
| Label | Text |
|---|---|
| A | SetOutString to"" |
| B | |
| C | |
| D | |
| E | SetIndex toIndex + 1 |
| F | |
| G |
Show mark scheme
7(a)
DECLARE IsPal : BOOLEAN DECLARE Index, Num : INTEGER DECLARE CharA, CharB : CHAR IsPal TRUE Index 1 Num INT(LENGTH(InString) / 2) WHILE Index <= Num AND IsPal = TRUE CharA MID(InString, Index, 1) CharB MID(Instring, LENGTH(Instring) – Index + 1, 1) IF UCASE(CharA) <> UCASE(CharB) THEN IsPal FALSE // RETURN FALSE ENDIF Index Index + 1 ENDWHILE RETURN IsPal // RETURN TRUE ENDFUNCTION Mark as follows: 1 Functions header including parameter, ending and return type 2 Calculation of number of pairs to match (length or half length) 3 Loop for half or whole string 4 …Extracting characters to compare // create reverse string 5 Convert characters to same case 6 Check for mismatch of characters inside loop / test for mismatch after loop for reversed string 7 Returning Boolean in both cases
7(b) [6 marks]
Label Text Set to A OutString "" Is B Index > LENGTH(InString)? Is
? C MID(InString, Index, 1) " " Set to OutString OutString & MID(InString, Index, D 1) Set to E Index Index + 1 F YES Mark for each of: B D C ...F and G Note : The mark for F and G is dependent on a reasonable attempt at C FUNCTION RandomChar() RETURNS CHAR
An algorithm is described as follows:
- Input an integer value.
- Jump to step 6 if the value is less than zero.
- Call the function
IsPrime()using the integer value as a parameter. - Keep a count of the number of times function
IsPrime()returnsTRUE. - Repeat from step 1.
- Output the value of the count with a suitable message.
Draw a program flowchart to represent the algorithm.
4 marks
Show mark scheme
2 Two loops to generate 3 groups of 4 characters // One loop to generate 12 / 14 characters
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) An algorithm to sort a 1D array into ascending order is described as follows: 6 marks
move the largest value to the end
keep repeating until the array is sorted.
Apply the process of stepwise refinement to this algorithm in order to produce a more detailed description.
Write the more detailed description using structured English . Your explanation of the algorithm should not include pseudocode statements.
Show mark scheme
2(a) [6 marks]
One mark for reference to: 1 The use a variable as an index to the array 2 A loop to iterate through the array 3 An Inner loop (with a reducing range) 4 Test if current element is greater than next element 5 if so then swap elements 6 Description of swap 7 Attempt at efficient algorithm Max 6 marks
2(b)
← Count 1 ← Flag FALSE WHILE Flag = FALSE AND Count <= 5 CALL ReBoot() ← Count Count + 1 ← Flag Check() ENDWHILE IF Flag = FALSE THEN CALL Alert(27) ENDIF One mark per point: 1 Initialisation of AND Count Flag 2 loop WHILE ... ENDWHILE // REPEAT ... UNTIL 3 ... including both conditions 4 Call AND increment inside the loop ReBoot() Count 5 Assign return value from to inside the loop Check() Flag 6 Final test of AND call to not in a loop Flag Alert(27)
(a) An algorithm will:
- input an integer value
- jump to step 6 if the value is zero
- sum and count the positive values
- sum and count the negative values
- repeat from step 1
- output the two sum values and the two count values.
Draw a program flowchart on the following page to represent the algorithm.
Note that variable declarations are not required in program flowcharts.
Show mark scheme
2(a) [2 marks]
One mark for each outlined group. Note: Sum and increment steps (bottom-right rectangles) may be in reverse • order in which case sum group will have two output lines Max 4 for non-working solution •
2(b)(i)
One mark for each: Life cycle method: Iterative // Rapid Application Development (RAD) Reason: Provides a working model / prototype at an early stage for the principal to approve / review
2(b)(ii) [3 marks]
Decisions will be made regarding: Data structures • Algorithms / flowcharts / pseudocode • Program structure (modules) / use of library routines / module - team • allocation User interface // Web-page layout / content (for given scenario) • Testing method / plan • Choice of programming language / program environment • Max 3
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
(a) An algorithm to sort a 1D array into ascending order is described as follows: 6 marks
move the largest value to the end
keep repeating until the array is sorted.
Apply the process of stepwise refinement to this algorithm in order to produce a more detailed description.
Write the more detailed description using structured English . Your explanation of the algorithm should not include pseudocode statements.
Show mark scheme
2(a) [6 marks]
One mark for reference to: 1 The use a variable as an index to the array 2 A loop to iterate through the array 3 An Inner loop (with a reducing range) 4 Test if current element is greater than next element 5 if so then swap elements 6 Description of swap 7 Attempt at efficient algorithm Max 6 marks
2(b)
← Count 1 ← Flag FALSE WHILE Flag = FALSE AND Count <= 5 CALL ReBoot() ← Count Count + 1 ← Flag Check() ENDWHILE IF Flag = FALSE THEN CALL Alert(27) ENDIF One mark per point: 1 Initialisation of AND Count Flag 2 loop WHILE ... ENDWHILE // REPEAT ... UNTIL 3 ... including both conditions 4 Call AND increment inside the loop ReBoot() Count 5 Assign return value from to inside the loop Check() Flag 6 Final test of AND call to not in a loop Flag Alert(27)
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 global 2D array Result of type INTEGER is used to store a list of exam candidate numbers
together with their marks. The array contains 2000 elements, organised as 1000 rows and
2 columns.
Column 1 contains the candidate number and column 2 contains the mark for the corresponding candidate. All elements contain valid exam result data.
A procedure Sort() is needed to sort Result into ascending order of mark using an efficient
bubble sort algorithm.
Write pseudocode for the procedure Sort() .
8 marks
Show mark scheme
5 [4 marks]
PROCEDURE Sort() DECLARE Temp : INTEGER DECLARE NoSwaps : BOOLEAN DECLARE Boundary, Row, Col : INTEGER ← Boundary 999 REPEAT ← NoSwaps TRUE ← FOR Row 1 TO Boundary IF Result[Row, 2] > Result[Row + 1, 2] THEN ← FOR Col 1 TO 2 ← Temp Result [Row, Col] ← Result [Row, Col] Result [Row + 1, Col] ← Result [Row + 1, Col] Temp NEXT Col ← NoSwaps FALSE ENDIF NEXT J ← Boundary Boundary - 1 UNTIL NoSwaps = TRUE ENDPROCEDURE Mark as follows: 1 Outer loop 2 Inner loop 3 Correct comparison in a loop 4 Correct swap of col1 array elements in a loop 5 Correct swap of col2 array elements in a loop (via loop or separate statements) 6 mechanism: Conditional outer loop including flag reset 'NoSwap' 7 mechanism: Set flag in inner loop to indicate swap 'NoSwap' 8 Reducing Boundary in the outer loop
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
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 global 2D array Result of type INTEGER is used to store a list of exam candidate numbers
together with their marks. The array contains 2000 elements, organised as 1000 rows and
2 columns.
Column 1 contains the candidate number and column 2 contains the mark for the corresponding candidate. All elements contain valid exam result data.
A procedure Sort() is needed to sort Result into ascending order of mark using an efficient
bubble sort algorithm.
Write pseudocode for the procedure Sort() .
8 marks
Show mark scheme
5 [4 marks]
PROCEDURE Sort() DECLARE Temp : INTEGER DECLARE NoSwaps : BOOLEAN DECLARE Boundary, Row, Col : INTEGER ← Boundary 999 REPEAT ← NoSwaps TRUE ← FOR Row 1 TO Boundary IF Result[Row, 2] > Result[Row + 1, 2] THEN ← FOR Col 1 TO 2 ← Temp Result [Row, Col] ← Result [Row, Col] Result [Row + 1, Col] ← Result [Row + 1, Col] Temp NEXT Col ← NoSwaps FALSE ENDIF NEXT J ← Boundary Boundary - 1 UNTIL NoSwaps = TRUE ENDPROCEDURE Mark as follows: 1 Outer loop 2 Inner loop 3 Correct comparison in a loop 4 Correct swap of col1 array elements in a loop 5 Correct swap of col2 array elements in a loop (via loop or separate statements) 6 mechanism: Conditional outer loop including flag reset 'NoSwap' 7 mechanism: Set flag in inner loop to indicate swap 'NoSwap' 8 Reducing Boundary in the outer loop