11.3· 20 questions · 191 marks · 229 min · 2021–2023· Structured questions
Every Cambridge A Level Computer Science Paper 2 question on structured programming, laid out as 38 A4 pages with the mark scheme below. Nothing is left out. Free to read, no account.
15 / 38
31 / 38
35 / 38Answers below. Sit the paper first if you are practising.
Pastlit
Computer Science 9618 · Structured Programming — Paper 2
A Level · topical answer key — answer key (teacher use)
Question
Answer
Marks
11
8
11
10
11
13
10
4
6
7
12
10
11
17
8
6
7
10
8
11| Question | Answer | Marks | From |
|---|---|---|---|
| 1 | see sheet | 11 | 9618/21 May/June 2021 |
| 2 | see sheet | 8 | 9618/22 May/June 2021 |
| 3 | see sheet | 11 | 9618/23 May/June 2021 |
| 4 | see sheet | 10 | 9618/21 Oct/Nov 2021 |
| 5 | see sheet | 11 | 9618/22 Oct/Nov 2021 |
| 6 | see sheet | 13 | 9618/22 Oct/Nov 2021 |
| 7 | see sheet | 10 | 9618/23 Oct/Nov 2021 |
| 8 | see sheet | 4 | 9618/21 May/June 2022 |
| 9 | see sheet | 6 | 9618/21 May/June 2022 |
| 10 | see sheet | 7 | 9618/23 May/June 2022 |
| 11 | see sheet | 12 | 9618/21 Oct/Nov 2022 |
| 12 | see sheet | 10 | 9618/21 Oct/Nov 2022 |
| 13 | see sheet | 11 | 9618/22 Oct/Nov 2022 |
| 14 | see sheet | 17 | 9618/23 Oct/Nov 2022 |
| 15 | see sheet | 8 | 9618/23 Oct/Nov 2022 |
| 16 | see sheet | 6 | 9618/21 May/June 2023 |
| 17 | see sheet | 7 | 9618/21 May/June 2023 |
| 18 | see sheet | 10 | 9618/22 May/June 2023 |
| 19 | see sheet | 8 | 9618/22 May/June 2023 |
| 20 | see sheet | 11 | 9618/23 May/June 2023 |
7 A program is needed to take a string containing a full name and produce a new string of initials. Some words in the full name will be ignored. For example, "the", "and", "of", "for" and "to" may all be ignored. Each letter of the abbreviated string must be upper case. For example: Full name Initials Integrated Development Environment IDE The American Standard Code for Information Interchange ASCII The programmer has decided to use a global variable FNString of type STRING to store the full name. It is assumed that: • words in the full name string are separated by a single space character • space characters will not occur at the beginning or the end of the full name string • the full name string contains at least one word. The programmer has started to define program modules as follows: Module Description • Called with an INTEGER as a parameter, representing the number of a word in FNString. • Returns the character start position of that word in FNString or GetStart() returns –1 if that word does not exist • For example: if FNString contains the string "hot and cold", GetStart(3) returns 9 • Called with a parameter representing the position of the first character of a word in FNString GetWord() • Returns the word from FNString • For example: if FNString contains the string "hot and cold", GetWord(9) returns "cold" (a) Write pseudocode for the module GetStart(). … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … [7] (b) The programmer has decided to use a global ten-element 1D array IgnoreList of type STRING to store the ignored words. Unused elements contain the empty string ("") and may occur anywhere in the array. A new module AddWord() is needed as follows: Module Description • Called with a parameter representing a word • Stores the word in an unused element of the IgnoreList array AddWord() and returns TRUE • Returns FALSE if the array was already full or if the word was already in the array Write a detailed description of the algorithm for AddWord(). Do not include pseudocode statements in your answer. … … … … … … … … … … … … [4]
11 marks
Mark scheme: 7(a) FUNCTION GetStart (WordNum : INTEGER) RETURNS INTEGER 7 DECLARE Index, ThisPos, NumFound : INTEGER DECLARE ThisChar : Char CONSTANT SPACECHAR = ' ' Index ← -1 Numfound ← 0 ThisPos ← 1 IF WordNum = 1 THEN // if looking for word 1... Index ← 1 // Word 1 always starts at index // position 1 ELSE // Otherwise start counting spaces... WHILE ThisPos <= LENGTH(FNString) AND Index = -1 ThisChar ← MID(FNString, ThisPos, 1) IF ThisChar = SPACECHAR THEN NumFound ← NumFound + 1 IF NumFound = WordNum - 1 THEN Index ← ThisPos + 1 // the start of the // required word ENDIF ENDIF ThisPos ← ThisPos + 1 ENDWHILE ENDIF RETURN Index ENDFUNCTION 1 mark for each of the following: 1 Function heading, including return type and function end 2 Loop counting spaces until word found or end of FNString 3 extract a character from FNString in a loop 4 compare with SPACECHAR and increment count if equal in a loop 5 compare count with WordNum - 1 (depending on initialisation value) in a loop 6 if equal then set flag or Index to ThisPos + 1 in a loop 7 Return Index (correctly in all cases / following a reasonable attempt) 8 Works for special case when looking for word 1 Note: Max 7 marks 7(b) Marks awarded for any reference to each of the following steps of the algorithm: 4 1 Mention of variable for use as array index 2 Use of a loop (to check through the array) 3 If word is the same as the current array element then return FALSE / set flag 4 If word not already in array, loop to find unused element (second loop) 5 Store word in unused element and return TRUE, otherwise return FALSE VARIATION: 1 Mention of variable for use as array index 2 Use of a loop (to check through the array) 3 Save index of (first) unused element found 4 If word is the same as the current array element then return FALSE / set flag 5 If word not already in array and unused element available, store word in unused element and return TRUE otherwise return FALSE Note: Max 4 marks 7(c) FUNCTION GetWord (Index : INTEGER) RETURNS STRING 5 DECLARE NextWord : STRING DECLARE Done : BOOLEAN DECLARE ThisChar : CHAR DECLARE Index : INTEGER CONSTANT SPACECHAR = ' ' NextWord ← "" Done ← FALSE REPEAT ThisChar ← MID(FNString, Index, 1) IF ThisChar <> SPACECHAR THEN NextWord ← NextWord & ThisChar // build up NextWord ENDIF IF ThisChar = SPACECHAR OR Index = LENGTH(FNString) THEN Done ← TRUE ENDIF Index ← Index + 1 UNTIL Done = TRUE RETURN NextWord ENDFUNCTION 1 mark for each of the following: 1 Conditional loop 2 Extract char from FNString and compare with SPACECHAR in a loop 3 Concatenate with NextWord if not SPACECHAR in a loop 4 Exit loop when SPACECHAR encountered or when end of FNString reached 5 Return NextWord (after reasonable attempt at forming, and must have been initialised) 7(c) The ‘length and substring’ solution: FUNCTION GetWord (Index : INTEGER) RETURNS STRING DECLARE Done : BOOLEAN DECLARE ThisChar : CHAR DECLARE Index, NextPos : INTEGER CONSTANT SPACECHAR = ' ' Done ← FALSE NextPos ← Index // must be at least one character in // the required word REPEAT ThisChar ← MID(FNString, NextPos, 1) IF ThisChar = SPACECHAR OR NextPos = LENGTH(FNString) THEN Done ← TRUE ELSE NextPos ← NextPos + 1 ENDIF UNTIL Done = TRUE IF NextPos = LENGTH(FNString) THEN NextPos ← NextPos - 1 // special case when last word ENDIF RETURN MID(FNString, Index, NextPos - Index) ENDFUNCTION 1 mark for each of the following: 1 Conditional loop 2 ...extract char from FNString and compare with SPACECHAR in a loop 3 .. increment count if word continues 4 Exit loop when SPACECHAR encountered or when end of FNString reached 5 Apply substring function and Return
6 A procedure CountVowels() will: • be called with a string containing alphanumeric characters as its parameter • count and output the number of occurrences of each vowel (a, e, i, o, u) in the string • count and output the number of occurrences of the other alphabetic characters (as a single total). The string may contain both upper and lower case characters. Each count value will be stored in a unique element of a global 1D array CharCount of type INTEGER. The array will contain six elements. Write pseudocode for the procedure CountVowels(). … … … … … … … … … … … … … … … … … … … … … … … … … … [8]
8 marks
Mark scheme: 6 PROCEDURE CountVowels(ThisString : STRING) 8 DECLARE Index : INTEGER DECLARE ThisChar : CHAR FOR Index ← 1 to 6 CharCount[Index] ← 0 //initialise elements NEXT Index Index ← 1 FOR Index ← 1 TO LENGTH(ThisString) ThisChar ← LCASE(MID(ThisString, Index, 1)) CASE OF ThisChar 'a' : CharCount[1] ← CharCount[1] + 1 'e' : CharCount[2] ← CharCount[2] + 1 'i' : CharCount[3] ← CharCount[3] + 1 'o' : CharCount[4] ← CharCount[4] + 1 'u' : CharCount[5] ← CharCount[5] + 1 'a' TO 'z': CharCount[6] ← CharCount[6] + 1 ENDCASE NEXT Index FOR Index ← 1 to 6 OUTPUT CharCount[Index] //output results NEXT Index ENDPROCEDURE 1 mark for each of the following: 1 Procedure heading (with parameter) and ending 2 Declare local variable for Index as loop counter but not CharCount array 3 Initialise elements of CharCount array to zero 4 Loop through all characters in ThisString 5 Use of MID() to extract single character 6 Test for each vowel and increment associated count 7 Test for consonants and increment associated count 8 Output the results (supporting text not necessary) after the loop Note: Max 7 if CharCount not used to store count
7 A program is needed to take a string containing a full name and produce a new string of initials. Some words in the full name will be ignored. For example, "the", "and", "of", "for" and "to" may all be ignored. Each letter of the abbreviated string must be upper case. For example: Full name Initials Integrated Development Environment IDE The American Standard Code for Information Interchange ASCII The programmer has decided to use a global variable FNString of type STRING to store the full name. It is assumed that: • words in the full name string are separated by a single space character • space characters will not occur at the beginning or the end of the full name string • the full name string contains at least one word. The programmer has started to define program modules as follows: Module Description • Called with an INTEGER as a parameter, representing the number of a word in FNString. • Returns the character start position of that word in FNString or GetStart() returns –1 if that word does not exist • For example: if FNString contains the string "hot and cold", GetStart(3) returns 9 • Called with a parameter representing the position of the first character of a word in FNString GetWord() • Returns the word from FNString • For example: if FNString contains the string "hot and cold", GetWord(9) returns "cold" (a) Write pseudocode for the module GetStart(). … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … [7] (b) The programmer has decided to use a global ten-element 1D array IgnoreList of type STRING to store the ignored words. Unused elements contain the empty string ("") and may occur anywhere in the array. A new module AddWord() is needed as follows: Module Description • Called with a parameter representing a word • Stores the word in an unused element of the IgnoreList array AddWord() and returns TRUE • Returns FALSE if the array was already full or if the word was already in the array Write a detailed description of the algorithm for AddWord(). Do not include pseudocode statements in your answer. … … … … … … … … … … … … [4]
11 marks
Mark scheme: 7(a) FUNCTION GetStart (WordNum : INTEGER) RETURNS INTEGER 7 DECLARE Index, ThisPos, NumFound : INTEGER DECLARE ThisChar : Char CONSTANT SPACECHAR = ' ' Index ← -1 Numfound ← 0 ThisPos ← 1 IF WordNum = 1 THEN // if looking for word 1... Index ← 1 // Word 1 always starts at index // position 1 ELSE // Otherwise start counting spaces... WHILE ThisPos <= LENGTH(FNString) AND Index = -1 ThisChar ← MID(FNString, ThisPos, 1) IF ThisChar = SPACECHAR THEN NumFound ← NumFound + 1 IF NumFound = WordNum - 1 THEN Index ← ThisPos + 1 // the start of the // required word ENDIF ENDIF ThisPos ← ThisPos + 1 ENDWHILE ENDIF RETURN Index ENDFUNCTION 1 mark for each of the following: 1 Function heading, including return type and function end 2 Loop counting spaces until word found or end of FNString 3 extract a character from FNString in a loop 4 compare with SPACECHAR and increment count if equal in a loop 5 compare count with WordNum - 1 (depending on initialisation value) in a loop 6 if equal then set flag or Index to ThisPos + 1 in a loop 7 Return Index (correctly in all cases / following a reasonable attempt) 8 Works for special case when looking for word 1 Note: Max 7 marks 7(b) Marks awarded for any reference to each of the following steps of the algorithm: 4 1 Mention of variable for use as array index 2 Use of a loop (to check through the array) 3 If word is the same as the current array element then return FALSE / set flag 4 If word not already in array, loop to find unused element (second loop) 5 Store word in unused element and return TRUE, otherwise return FALSE VARIATION: 1 Mention of variable for use as array index 2 Use of a loop (to check through the array) 3 Save index of (first) unused element found 4 If word is the same as the current array element then return FALSE / set flag 5 If word not already in array and unused element available, store word in unused element and return TRUE otherwise return FALSE Note: Max 4 marks 7(c) FUNCTION GetWord (Index : INTEGER) RETURNS STRING 5 DECLARE NextWord : STRING DECLARE Done : BOOLEAN DECLARE ThisChar : CHAR DECLARE Index : INTEGER CONSTANT SPACECHAR = ' ' NextWord ← "" Done ← FALSE REPEAT ThisChar ← MID(FNString, Index, 1) IF ThisChar <> SPACECHAR THEN NextWord ← NextWord & ThisChar // build up NextWord ENDIF IF ThisChar = SPACECHAR OR Index = LENGTH(FNString) THEN Done ← TRUE ENDIF Index ← Index + 1 UNTIL Done = TRUE RETURN NextWord ENDFUNCTION 1 mark for each of the following: 1 Conditional loop 2 Extract char from FNString and compare with SPACECHAR in a loop 3 Concatenate with NextWord if not SPACECHAR in a loop 4 Exit loop when SPACECHAR encountered or when end of FNString reached 5 Return NextWord (after reasonable attempt at forming, and must have been initialised) 7(c) The ‘length and substring’ solution: FUNCTION GetWord (Index : INTEGER) RETURNS STRING DECLARE Done : BOOLEAN DECLARE ThisChar : CHAR DECLARE Index, NextPos : INTEGER CONSTANT SPACECHAR = ' ' Done ← FALSE NextPos ← Index // must be at least one character in // the required word REPEAT ThisChar ← MID(FNString, NextPos, 1) IF ThisChar = SPACECHAR OR NextPos = LENGTH(FNString) THEN Done ← TRUE ELSE NextPos ← NextPos + 1 ENDIF UNTIL Done = TRUE IF NextPos = LENGTH(FNString) THEN NextPos ← NextPos - 1 // special case when last word ENDIF RETURN MID(FNString, Index, NextPos - Index) ENDFUNCTION 1 mark for each of the following: 1 Conditional loop 2 ...extract char from FNString and compare with SPACECHAR in a loop 3 .. increment count if word continues 4 Exit loop when SPACECHAR encountered or when end of FNString reached 5 Apply substring function and Return
5 The following data items will be recorded each time a student successfully logs on to the school network: Data item Example data Student ID "CJL404" Host ID "Lib01" Time and date "08:30, June 01, 2021" The Student ID is six characters long. The other two data items are of variable length. A single string will be formed by concatenating the three data items. A separator character will need to be inserted between items two and three. For example: "CJL404Lib01<separator>08:30, June 01, 2021" Each string represents one log entry. A programmer decides to store the concatenated strings in a 1D array LogArray that contains 2000 elements. Unused array elements will contain an empty string. (a) Suggest a suitable separator character and give a reason for your choice. Character … Reason … … [2] (b) The choice of data structure was made during one stage of the program development life cycle. Identify this stage. … [1] (c) A function LogEvents() will: • take a Student ID as a parameter • for each element in the array that matches the Student ID parameter: ◦ add the value of the array element to the existing text file LogFile ◦ assign an empty string to the array element • count the number of lines added to the file • return this count. Write pseudocode for the function LogEvents(). … … … … … … … … … … … … … … … … … … … … … … … … [7]
10 marks
Mark scheme: 5(a) One mark for the character and one for the corresponding reason. 2 • Character: Any except alphabetic, numeric, ',' ':' or space • Reason: character doesn't occur in data to be recorded 5(b) Design 1 5(c) FUNCTION LogEvents(StudentID : STRING) RETURNS INTEGER 7 DECLARE FileData : STRING DECLARE Index, Count : INTEGER CONSTANT LogFile = "LogFile" Count ← 0 OPENFILE LogFile FOR APPEND FOR Index ← 1 TO 2000 FileData ← LogArray[Index] IF LEFT(FileData, 6) = StudentID THEN WRITEFILE (LogFile, FileData) //brackets optional Count ← Count + 1 LogArray[Index] ← "" // clear the element ENDIF NEXT Index CLOSEFILE LogFile RETURN Count ENDFUNCTION 1 mark for each of the following: 1 Function heading and ending including parameter and return type 2 OPEN file LogFile for APPEND and subsequent CLOSE 3 Loop for 2000 iterations 4 Extract first 6 characters from array element in a loop 5 Compare first 6 characters with parameter in a loop 6 If equal: • write whole array element string to file and • increment Count and • clear array element in a loop 7 Return Count (must have been declared and initialised)
4 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 to STR_TO_NUM() The name of a procedure other than Check() [5] (b) The pseudocode includes several features that make it easier to read and understand. Identify three of these features. 1 … 2 … 3 … [3] (c) (i) The loop structure used in the pseudocode is not the most appropriate. State a more appropriate loop structure and justify your choice. Loop structure … Justification … … … [2] (ii) The appropriate loop structure is now used. Two lines of pseudocode are changed and two lines are removed. Write the line numbers of the two lines that are removed. … … [1]
11 marks
Mark scheme: 4(a) 5 Answer A line number containing a variable being incremented 19 / 21 / 23 The type of loop structure pre-condition The number of functions used 3 The number of parameters passed to function 1 STR_TO_NUM() The name of a procedure other than Check() Result 4(b) One mark per point: 3 • Meaningful variable names • Indentation / white space / blank lines • Capitalisation of keywords 4(c)(i) One mark per point: 2 Structure: A count-controlled loop Justification: The number of iterations is known // repeats for the length of InString 4(c)(ii) 15, 23 1 One mark for both line numbers
6 A mobile phone has a touchscreen. The screen is represented by a grid, divided into 800 rows and 1280 columns. The grid is represented by a 2D array Screen of type INTEGER. An array element will be set to 0 unless the user touches that part of the screen. Many array elements will set to 1 by a single touch of a finger or a stylus. The following diagram shows a simplified touchscreen. The dark line represents a touch on the screen. All grid elements that are wholly or partly inside the outline will be set to 1. These elements are shaded. The element shaded in black represents the centre point of the touch. 11 6 A program is needed to find the coordinates (the row and column) of the centre point. The centre point on the diagram shown is row 6, column 11. Assume: • the user may only touch one area at a time • screen rotation does not affect the touchscreen. The programmer has decided to use global values CentreRow and CentreCol as coordinate values for the centre point. The programmer has started to define program modules as follows: Module Description • Searches for the first row that has an array element set to 1 FirstRowSet() • Returns the index of that row (1 is the first row) • Returns −1 if there are no elements set to 1 • Searches for the last row that has an array element set to 1 LastRowSet() • Returns the index of that row • Returns −1 if there are no elements set to 1 • Searches for the first column that has an array element set to 1 FirstColSet() • Returns the index of that column (1 is the first column) • Returns −1 if there are no elements set to 1 • Searches for the last column that has an array element set to 1 LastColSet() • Returns the index of that column • Returns −1 if there are no elements set to 1 (a) Write efficient pseudocode for the module FirstRowSet(). … … … … … … … … … … … … … … … … … … … … … … … … … … … … (b) Describe a feature of your solution to part (a) that indicates the pseudocode represents an efficient algorithm. … … … … [2] (c) The programmer decides to produce a single search module FindSet(), which will be able to perform each of the individual searches performed by the first four modules in the table. (i) Outline the changes needed to convert one of the existing modules into this single module. … … … … … … [2] (ii) Give one possible advantage and one possible disadvantage of combining the four searches into a single module. Advantage … … Disadvantage … … [2]
13 marks
Mark scheme: 6(a) FUNCTION FirstRowSet() RETURNS INTEGER 7 DECLARE Row, Col : INTEGER DECLARE Found : BOOLEAN // array is 1280 × 800 Row ← 1 Found ← FALSE WHILE Row <= 800 AND Found = FALSE // top to bottom Col ← 1 WHILE Col <= 1280 AND Found = FALSE // left to right IF Screen[Row,Col] = 1 THEN Found ← TRUE // end function as soon as first // found ENDIF Col ← Col + 1 ENDWHILE Row ← Row + 1 ENDWHILE IF Found = FALSE THEN // nothing found Row ← 0 ENDIF RETURN Row - 1 ENDFUNCTION Mark as follows: 1 Function heading and ending and return type 2 (Conditional) outer loop 1 to 800 (row) 3 (Conditional) inner loop 1 to 1280 // 1280 to 1 (column) 4 Reference Screen element and test for = 1 // <> 0 5 and if true save row number and exit loops 6 Increment index variables in both inner and outer loop 7 Return Row number or −1, following a reasonable attempt 6(b) One mark for: 2 • (A flag is used to) exit the loops // iteration is terminated • as soon as a Screen element with value 1 is found 6(c)(i) One mark for: 2 • Parameter(s) need to be passed to the module to identify the type of search • Search algorithm is controlled by (global) variables / parameters Alternative: • The search algorithms from the original modules are included in the new module • The new module needs to return / store the four values (the results of the four searches) 6(c)(ii) One mark for advantage and one for disadvantage: 2 Advantage: (max 1) • Only have to change one module if specification changes • Less repetitive code / fewer lines of code • Aids re-usability Disadvantage: (max 1) • Single module more complex / more error prone / more difficult to debug ... • Single module cannot be split among programmers / teams Max 2 6(d) PROCEDURE GetCentre () 6 DECLARE StartRow, EndRow, StartCol, EndCol : INTEGER StartRow ← FirstRowSet() IF StartRow = -1 THEN CentreRow ← -1 // no 'touch' detected ELSE EndRow ← LastRowSet() StartCol ← FirstColSet() EndCol ← LastColSet() CentreRow ← INT((StartRow + EndRow)/2) CentreCol ← INT((StartCol + EndCol)/2) ENDIF ENDPROCEDURE Mark as follows: 1 Call <any Set function> and check for -1 // check for no element set 2 ...and if so set CentreRow to –1 3 Call all 4 Set functions to get 'extremity' values 4 Calculate centre row and centre column 5 Use of INT() function or DIV operator on values from MP4 6 Assign calculated values to CentreRow and CentreCol Note: Max 5 if procedure heading and ending missing or incorrect (ignore array if passed as a parameter) or any local variables are undefined or of incorrect type
5 The following data items will be recorded each time a student successfully logs on to the school network: Data item Example data Student ID "CJL404" Host ID "Lib01" Time and date "08:30, June 01, 2021" The Student ID is six characters long. The other two data items are of variable length. A single string will be formed by concatenating the three data items. A separator character will need to be inserted between items two and three. For example: "CJL404Lib01<separator>08:30, June 01, 2021" Each string represents one log entry. A programmer decides to store the concatenated strings in a 1D array LogArray that contains 2000 elements. Unused array elements will contain an empty string. (a) Suggest a suitable separator character and give a reason for your choice. Character … Reason … … [2] (b) The choice of data structure was made during one stage of the program development life cycle. Identify this stage. … [1] (c) A function LogEvents() will: • take a Student ID as a parameter • for each element in the array that matches the Student ID parameter: ◦ add the value of the array element to the existing text file LogFile ◦ assign an empty string to the array element • count the number of lines added to the file • return this count. Write pseudocode for the function LogEvents(). … … … … … … … … … … … … … … … … … … … … … … … … [7]
10 marks
Mark scheme: 5(a) One mark for the character and one for the corresponding reason. 2 • Character: Any except alphabetic, numeric, ',' ':' or space • Reason: character doesn't occur in data to be recorded 5(b) Design 1 5(c) FUNCTION LogEvents(StudentID : STRING) RETURNS INTEGER 7 DECLARE FileData : STRING DECLARE Index, Count : INTEGER CONSTANT LogFile = "LogFile" Count ← 0 OPENFILE LogFile FOR APPEND FOR Index ← 1 TO 2000 FileData ← LogArray[Index] IF LEFT(FileData, 6) = StudentID THEN WRITEFILE (LogFile, FileData) //brackets optional Count ← Count + 1 LogArray[Index] ← "" // clear the element ENDIF NEXT Index CLOSEFILE LogFile RETURN Count ENDFUNCTION 1 mark for each of the following: 1 Function heading and ending including parameter and return type 2 OPEN file LogFile for APPEND and subsequent CLOSE 3 Loop for 2000 iterations 4 Extract first 6 characters from array element in a loop 5 Compare first 6 characters with parameter in a loop 6 If equal: • write whole array element string to file and • increment Count and • clear array element in a loop 7 Return Count (must have been declared and initialised)
3 The manager of a cinema wants a program to allow users to book seats. The cinema has several screens. Each screen shows a different film. (a) Decomposition will be used to break the problem down into sub-problems. Describe three program modules that could be used in the design. Module 1 … … … Module 2 … … … Module 3 … … … [3] (b) Two types of program modules may be used in the design of the program. Identify the type of program module that should be used to return a value. … [1]
4 marks
Mark scheme: 3(a) One mark per description of appropriate sub-problem for given scenario. 3 Examples include: Allows the user to search for films being shown // input name of film they want to see Allows the user to search for available seats Calculate cost of booking Book a given number of seats for a particular screening 3(b) Function 1
8 A program allows a user to save passwords used to login to websites. A stored password is inserted automatically when the user logs into the corresponding website. A student is developing a program to generate a password. The password will be of a fixed format, consisting of three groups of four alphanumeric characters. The groups are separated by the hyphen character '-'. An example of a password is: "FxAf-3haV-Tq49" A global 2D array Secret of type STRING stores the passwords together with the website domain name where they are used. Secret contains 1000 elements organised as 500 rows by 2 columns. Unused elements contain the empty string (""). These may occur anywhere in the array. An example of a part of the array is: Array element Value Secret[27, 1] "www.thiswebsite.com" Secret[27, 2] Secret[28, 1] "www.thatwebsite.com" Secret[28, 2] Note: • For security, passwords are stored in an encrypted form, shown as "" in the example. • The passwords cannot be used without being decrypted. • Assume that the encrypted form of a password will not be an empty string. The programmer has started to define program modules as follows: Module Description RandomChar() • Generates a single random character from within one of the following ranges: ○ 'a' to 'z' ○ 'A' to 'Z' ○ '0' to '9' • Returns the character Encrypt() • Takes a password as a parameter of type string • Returns the encrypted form of the password as a string Decrypt() • Takes an encrypted password as a parameter of type string • Returns the decrypted form of the password as a string For reference, relevant ASCII values are as follows: Character range ASCII range 'a' to 'z' 97 to 122 'A' to 'Z' 65 to 90 '0' to '9' 48 to 57 (a) Write pseudocode for module RandomChar(). You may wish to refer to the insert for a description of the CHR() function. Other functions may also be required. … … … … … … … … … … … … … … … … … … … [6] (b) A new module is defined as follows: Module Description FindPassword() • Takes a website domain name as a parameter of type string • Searches for the website domain name in the array Secret • If the website domain name is found, the decrypted password is returned • If the website domain name is not found, a warning message is output, and an empty string is returned Write pseudocode for module FindPassword(). Assume that modules Encrypt() and Decrypt() have already been written. … … … … … … … … … … … … … … … … … … … …
6 marks
Mark scheme: 8(a) FUNCTION RandomChar() RETURNS CHAR 6 DECLARE ThisRange : INTEGER DECLARE ThisChar : CHAR //First select the range ThisRange INT(RAND(3)) + 1 // 1 to 3 CASE OF ThisRange 1: ThisChar CHR(INT(RAND(26) + 65)) // 65 to 90: 'A' to 'Z' ThisChar LCASE(ThisChar) // 'a' to 'z' 2: ThisChar CHR(INT(RAND(26) + 65)) // 65 to 90: A to Z 3: ThisChar NUM_TO_STR(INT(RAND(10)) // '0' to '9' ENDCASE RETURN ThisChar ENDFUNCTION Mark as follows: 1 Generation of any integer random number 2 Randomly decide which of the three ranges to select 3 Selection structure based on range 4 One alphanumeric character range correct 5 All alphanumeric character ranges correct 6 Return ThisChar, following a reasonable attempt to generate a character in each range 8(b) FUNCTION FindPassword(Name: STRING) RETURNS STRING 7 DECLARE Index : INTEGER DECLARE Password : STRING Password "" Index 1 WHILE Password = "" AND Index <= 500 IF Secret[Index, 1] = Name THEN Password Decrypt(Secret[Index, 2]) ELSE Index Index + 1 ENDIF ENDWHILE IF Password = "" THEN OUTPUT "Domain name not found" ENDIF RETURN Password ENDFUNCTION Mark as follows: 1 Declare all local variables used, attempted solution has to be reasonable 2 Conditional loop while not found and not end of array 3 Compare value of element in column 1 with parameter passed into function 4 ...and use Decrypt() with element in column 2 as parameter 5 …use the return value of Decrypt() 6 Output warning message if parameter not found 7 Return STRING value 8(c) One mark for the name, one for the description 3 Name: Stub testing Description: A simple module is written to replace each of the modules. The simple module will return an expected value // will output a message to show they have been called 8(d) Accept one example of a valid password to Max 2 2 One mark for each password example that breaks one of the rules due to: Length too long // length too short Invalid character Incorrect grouping (including number of hyphens) Duplicated characters 8(e) One mark for each part: 3 Generate a random integer divisible by 3 Split range into 1/3 and set as numeric Else alphabetic character
9 A program allows a user to save passwords used to log in to websites. A stored password is then inserted automatically when the user logs in to the corresponding website. A student is developing a program to generate a strong password. The password will be of a fixed format, consisting of three groups of four alphanumeric characters, separated by the hyphen character '-'. An example of a password is: "FxAf-3hzV-Aq49" A valid password: • must be 14 characters long • must be organised as three groups of four alphanumeric characters. The groups are separated by hyphen characters • may include duplicated characters, provided these appear in different groups. The programmer has started to define program modules as follows: Module Description • Generates a single random character from within one of the following ranges: ○ 'a' to 'z' RandomChar() ○ 'A' to 'Z' ○ '0' to '9' • Returns the character • Takes two parameters: ○ a string ○ a character Exists() • Performs a case-sensitive search for the character in the string • Returns TRUE if the character occurs in the string, otherwise returns FALSE • Generates a valid password Generate() • Uses RandomChar() and Exists() • Returns the password Note: in a case-sensitive comparison, 'a' is not the same as 'A'. (a) Write pseudocode for the module Generate(). … … … … … … … … … … … … … … … … … … … … … … … … … … … [7] (b) A global 2D array Secret of type STRING stores the passwords together with the website domain name where they are used. Secret contains 1000 elements organised as 500 rows by 2 columns. Unused elements contain the empty string (""). These may occur anywhere in the array. An example of part of the array is: Array element Value Secret[27, 1] "www.thiswebsite.com" Secret[27, 2] Secret[28, 1] "www.thatwebsite.com" Secret[28, 2] Note: • For security, the passwords are stored in an encrypted form, shown as "●●●●●●●●●●●●" in the example. • The passwords cannot be used without being decrypted. • You may assume that the encrypted form of a password will not be an empty string. Additional modules are defined as follows: Module Description • Takes a password as a string Encrypt() • Returns the encrypted form of the password as a string • Takes an encrypted password as a string Decrypt() • Returns the decrypted form of the password as a string • Takes a website domain name as a string • Searches for the website domain name in the array Secret • If the website domain name is found, the decrypted password is FindPassword() returned • If the website domain name is not found, an empty string is returned • Takes two parameters as strings: a website domain name and a password • Searches for the website domain name in the array Secret and AddPassword() if not found, adds the website domain name and the encrypted password to the array • Returns TRUE if the website domain name and encrypted password are added to the array, otherwise returns FALSE The first three modules have been written.
7 marks
Mark scheme: 9(a) FUNCTION Generate() RETURNS STRING 7 DECLARE Password, Group : STRING DECLARE NextChar : CHAR DECLARE ACount, BCount : INTEGER CONSTANT HYPHEN = '-' Password "" FOR ACount 1 TO 3 Group "" FOR BCount 1 TO 4 REPEAT NextChar RandomChar() UNTIL Exists(Group, NextChar) = FALSE Group Group & NextChar NEXT BCount Password Password & Group & HYPHEN NEXT ACount Password LEFT(Password, 14) // remove final hyphen RETURN Password ENDFUNCTION Marks as follows to Max 7: 1 Declaration and initialisation of Password as STRING 2 Outer loop for three groups / until password is complete // three group loops 3 Attempt to use of both RandomChar() and Exists()in a loop 4 (Inner) loop for 4 characters in a group // note every 4 chars in a loop 5 Conditional loop until char is unique 6 Concatenating unique character to Group in a loop 7 Concatenate Group / random character to Password in a loop 8 (Attempt to) insert hyphens between groups (or removing later) and Return Password 9(b) FUNCTION AddPassword(Name, Password : STRING) 6 RETURNS BOOLEAN DECLARE Index : INTEGER DECLARE Added : BOOLEAN Added FALSE Index 1 IF FindPassword(Name) = "" THEN // Domain name not in // array WHILE Added = FALSE AND Index <= 500 IF Secret[Index, 1] = "" THEN Secret[Index, 1] Name Secret[Index, 2] Encrypt(Password) Added TRUE ELSE Index Index + 1 ENDIF ENDWHILE ENDIF RETURN Added ENDFUNCTION Marks as follows: 1 Check that the website domain name isn't already in array using FindPassword() / linear search, otherwise: 2 (Conditional) loop while not added and not end of array 3 Check for unused element by testing value in column 1 in a loop 4 If unused, write parameter values to column 1 and 2 and set flag / variable 5 ...having used Encrypt() on the password 6 Return BOOLEAN value (correctly in all cases) 9(c) One mark per point to Max 3. 3 Solution based on field length: Convert the length of the website domain name (either field) … … to a string of fixed length Form a string by concatenate this string with the other two (and write as one line of the file) Solution based on use of separator character: Select a (separator) character that cannot occur in the domain name (e.g. space) Create a string from the domain name followed by the separator ...Concatenate the encrypted password (and write as one line of the file)
1 (a) An algorithm includes a number of complex calculations. A programmer is writing a program to implement the algorithm and decides to use library routines to provide part of the solution. State three possible benefits of using library routines in the development of the program. 1 … … 2 … … 3 … … [3] (b) The following pseudocode is part of a program that stores names and test marks for use in other parts of the program. DECLARE Name1, Name2, Name3 : STRING DECLARE Mark1, Mark2, Mark3 : INTEGER INPUT Name1 INPUT Mark1 INPUT Name2 INPUT Mark2 INPUT Name3 INPUT Mark3 (i) The pseudocode needs to be changed to allow for data to be stored for up to 30 students. Explain why it would be good practice to use arrays to store the data. … … … … … … [3] (ii) The following pseudocode statement includes array references: OUTPUT "Student ", Name[Count], " scored ", Mark[Count] State the purpose of the variable Count and give its data type. Purpose … … Data type … [2] (c) The pseudocode statements in the following table may contain errors. State the error in each case or write ‘NO ERROR’ if the statement contains no error. Assume that any variables used are of the correct type for the given function. Statement Error IF EMPTY "" THEN ← Status IS_NUM(-23.4) ← X STR_TO_NUM("37") + 5 ← Y STR_TO_NUM("37" + "5") ← [4]
12 marks
Mark scheme: Question Answer Marks 1(a) One mark per point: 3 1 They are tried and tested so free from errors 2 They perform a function that you may not be able to program yourself (for example encryption) 3 They are readily available / speed up development time 1(b)(i) One mark per point: 3 1 Algorithm to process / search / organise the data is easier to implement // Values may be accessed via a loop-controlled variable / iterated through using index 2 Makes the program easier to design / code / test / understand 3 Multiple instances referenced via a single identifier / so fewer identifiers needed // Easier to amend the program when the number of students increases 1(b)(ii) One mark per point: 2 Purpose: It identifies / references an individual array element // provides the index to the array Data type: Integer 1(c) One mark per row: 4 Statement Error IF EMPTY "" THEN Should be "=" not Status IS_NUM(-23.4) Parameter should be a string (or char) // should not be a real X STR_TO_NUM("37") + 5 NO ERROR Y STR_TO_NUM("37" + "5") Wrong operator – should be & or Parameter is not a string
7 A simple arithmetic expression is stored as a string in the format: <Value1><Operator><Value2> An operator character is one of the following: ' + ' ' − ' ' * ' ' / ' Example arithmetic expression strings: "803+1904" "34/7" (a) A procedure Calculate() will: • take an arithmetic expression string as a parameter • evaluate the expression • output the result. Assume: • the string contains only numeric digits and a single operator character • Value1 and Value2 represent integer values • Value1 and Value2 are unsigned (they will not be preceded by ' + ' or ' − '). (i) Write pseudocode for the procedure Calculate(). … … … … … … … … … … … … … … … … … … … … … … … … … … … … [7] (ii) Calculate() is changed to a function that returns the value of the evaluated expression. Write the header for the function in pseudocode. … … [1] (b) A string representing an arithmetic expression could be in the correct format but be impossible to evaluate. Give an example of a correctly formatted string and explain why evaluation would be impossible. Example string … Explanation … … … [2]
10 marks
Mark scheme: 7(a)(i) One mark per point (Max 7) as follows: 7 1 Declaration of local variables for Par1 Par2 and Par3 2 Loop to end of (parameter) string // until operator is found 3 Extract a character in a loop... 4 Attempt at extraction of three parts of expression using substring functions 5 Completely correct extraction of all three parts of expression 6. Convert string to Integer using STR_TO_NUM(<something sensible>) 7 Attempt to interpret at least two operators (Par2): + - * / 8 Corresponding correct calculation (all operators) and final Output of result PROCEDURE Calculate(Expression : STRING) DECLARE Val1, Val2, Index : INTEGER DECLARE Result : REAL DECLARE Par1, Par2, Par3 : STRING CONSTANT PLUS = '+' CONSTANT MINUS = '-' CONSTANT MULTIPLY = '*' CONSTANT DIVIDE = '/' FOR Index 1 TO LENGTH(Expression) //search for operator ThisChar MID(Expression, Index, 1) IF IS_NUM(ThisChar) = FALSE THEN Par1 LEFT(Expression, Index – 1) Par2 ThisChar Par3 RIGHT(Expression, LENGTH(Expression) – Index) ENDIF NEXT Index Val1 STR_TO_NUM(Par1) Val2 STR_TO_NUM(Par3) CASE OF Par2 PLUS : Result Val1 + Val2 MINUS : Result Val1 - Val2 MULTIPLY : Result Val1 * Val2 DIVIDE : Result Val1 / Val2 ENDCASE OUTPUT Result ENDPROCEDURE 7(a)(ii) FUNCTION Calculate(Expression : STRING) RETURNS REAL 1 7(b) Example string: "23/0" (Any divide by zero example) 2 Reason: The result is infinity / cannot be represented / is undefined // will cause the program to crash
1 (a) A programmer is developing an algorithm to solve a problem. Part of the algorithm would be appropriate to implement as a subroutine (a procedure or a function). (i) State two reasons why the programmer may decide to use a subroutine. 1 … … 2 … … [2] (ii) A procedure header is shown in pseudocode: PROCEDURE MyProc(Count : INTEGER, Message : STRING) Give the correct term for the identifiers Count and Message and explain their use. Term … Use … … … … [2] (b) The algorithm in part (a) is part of a program that will be sold to the public. All the software errors that were identified during in-house testing have been corrected. Identify and describe the additional test stage that may be carried out before the program is sold to the public. Test stage … Description … … … … … … [4] (c) Part of an identifier table is shown: Variable Type Example value FlagDay DATE 23/04/2004 CharList STRING "ABCDEF" Count INTEGER 29 Complete the table by evaluating each expression using the example values. Expression Evaluation MID(CharList, MONTH(FlagDay), 1) INT(Count / LENGTH(CharList)) (Count >= 29) AND (DAY(FlagDay) > 23) [3]
11 marks
Mark scheme: Question Answer Marks 1(a)(i) One mark for each point (Max 2): 2 • When a task which is repeated / reused / performed in several places • When a part of an algorithm performs a specific task • Reduces complexity of program / program is simplified // subroutine already available • Testing / debugging / maintenance is easier 1(a)(ii) One mark for each part: 2 Term: Parameter(s) Use: to pass values / arguments to the procedure 1(b) One mark for test stage, one mark for each description point 4 (Max 3 for Description) Test stage: Beta testing Description: 1 Testing carried out by a small group of (potential) users 2 Users will check that the software works as required / works in the real world / does not contain errors 3 Users will feedback problems / suggestions for improvement 4 Problems / suggestions identified are addressed (before the program is sold) 1(c) One mark per row: 3 Expression Evaluation MID(CharList, MONTH(FlagDay), 1) 'D' INT(Count / LENGTH(CharList)) 4 (Count >= 99) AND (DAY(FlagDay) > 23) FALSE
5 (a) A text string contains three data items concatenated as shown: <StockID><Description><Cost> Item lengths are: Item Length StockID 5 Description 32 Cost the remainder of the string A procedure Unpack() takes four parameters of type string. One parameter is the original text string. The other three parameters are used to represent the three data items shown in the table and are assigned values within the procedure. These values will be used by the calling program after the procedure ends. (i) Write pseudocode for the procedure Unpack(). … … … … … … … … … … [6] (ii) Explain the term procedure interface with reference to procedure Unpack(). … … … … [2] (b) The design changes and a record structure is defined to store the three data items. A user-defined data type StockItem is created as shown: TYPE StockItem DECLARE StockID : STRING DECLARE Description : STRING DECLARE Cost : REAL ENDTYPE (i) A variable LineData of type StockItem is declared. Write the pseudocode statement to assign the value 12.99 to the Cost field of LineData. … [1] (ii) Procedure Unpack() is modified and converted to a function which takes the original text string as the only parameter. Explain the other changes that need to be made to convert the procedure into a function. … … … … … [2] (c) Unpack() is part of a program made up of several modules. During the design stage, it is important to follow good programming practice. One example of good practice is the use of meaningful identifier names. Give the reason why this is good practice. Give two other examples of good practice. Reason … … … Example 1 … … … Example 2 … … … [3] (d) The program that includes Unpack() is tested using the walkthrough method. Describe this method and explain how it can be used to identify an error. … … … … … … [3]
17 marks
Mark scheme: 5(a)(i) One mark per point: 6 1 Procedure heading and ending including four parameters... 2 ...and use of BYREF for the three extracted values 3 Extract and assign SID 4 Extract and assign SDesc 5 Calculation of length of SCost (remainder of string) 6 Extract and assign SCost following an attempt at MP5 PROCEDURE UnPack(BYVAL TLine : STRING, BYREF SID, SDesc, SCost : STRING) SID LEFT(TLine, 5) SDesc MID(TLine, 6, 32) SCost RIGHT(TLine, LENGTH(TLine) – 37) ENDPROCEDURE 5(a)(ii) One mark each (Max 2): 2 1 Provides a mechanism to allow calling program to pass data 2 Defines the four parameters of Unpack() 3 … giving their data type and order 5(b)(i) LineData.Cost 12.99 1 5(b)(ii) One mark per point (Max 2): 2 • The new function will return an item of type StockItem • Need to declare/use a (local) variable of type StockItem • Costfield needs to be converted from a string to a real 5(c) One mark for reason 3 One mark for each example (Max 2) Reason: • Makes the code easier to understand // Describes the purpose of the identifier // Makes the code easier to debug/test/maintain Further examples include: • White space • Indentation • Keywords in capitals • Comments • Local variables // parameters 5(d) One mark per point (Max 3) 3 1 The program is checked by creating a trace table / going through the program a line at a time 2 ….to record/check variable (values) as they change 3 Error may be indicated when variable given an unexpected value 4 Error may be indicated by an unexpected path through the program // Faults in the logic of the program can be detected
7 A teacher is designing a program to perform simple syntax checks on programs written by students. Two global 1D arrays are used to store the syntax error data. Both arrays contain 500 elements. • Array ErrCode contains integer values that represent an error number in the range 1 to 800. • Array ErrText contains string values that represent an error description. The following diagram shows an example of the arrays. Index ErrCode ErrText 1 10 "Invalid identifier name" 2 20 "Bracket mismatch" 3 50 "" 4 60 "Type mismatch in assignment" ... 500 999 <Undefined> Note: • There are less than 500 error codes so corresponding elements in both arrays may be unused. Unused elements in ErrCode have the value 999. These will occur at the end of the array. The value of unused elements in ErrText is undefined. • Values in the ErrCode array are stored in ascending order but not all values may be present. For example, there may be no error code 31. • Some error numbers are undefined. In these instances, the ErrCode array will contain a valid error number but the corresponding ErrText element will contain an empty string. The teacher has defined one program module as follows: Module Description • Prompts for input of two error numbers • Outputs a list of error numbers between the two numbers input (inclusive) together with the corresponding error description • Outputs a warning message when the error description is missing as for error number 50 in the example • Outputs a suitable header and a final count of error numbers found OutputRange() Output based on the example array data above: List of error numbers from 1 to 60 10 : Invalid identifier name 20 : Bracket mismatch 50 : Error Text Missing 60 : Type mismatch in assignment 4 error numbers output (a) Write pseudocode for module OutputRange(). Assume that the two numbers input represent a valid error number range. … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … … [8]
8 marks
Mark scheme: 7(a) One mark per point (Max 8): 8 1 Declaration and initialisation of local integer for Count 2 Appropriate prompt and two inputs 3 (Conditional) loop while error number input is in range // error code 999 reached 4 …and not end of array 5 Check if this ErrCode needs to be output in a loop 6 if so check for blank error text in a loop 7 Output in both cases 8 ….and increment count in a loop 9 OUTPUT of header and summary including count PROCEDURE OutputRange() DECLARE First, Last, Count, Index, ThisErr : INTEGER DECLARE ThisMess : STRING DECLARE PastLast: BOOLEAN Count 0 Index 1 PastLast FALSE OUTPUT "Please input first error number: " INPUT First OUTPUT "Please input last error number: " INPUT Last OUTPUT "List of error numbers from ", First, " to ", Last WHILE Index < 501 AND NOT PastLast ThisErr ErrCode[Index] IF ThisErr > Last THEN PastLast TRUE ELSE IF ThisErr >= First THEN ThisMess ErrText[Index] IF ThisMess = "" THEN ThisMess "Error Text Missing" ENDIF OUTPUT ThisErr, " : ", ThisMess Count Count + 1 ENDIF ENDIF Index Index + 1 ENDWHILE OUTPUT Count, " error numbers output" ENDPROCEDURE 7(b)(i) One mark per point: 6 1 (Conditional) loop terminating when item added OR end of array reached 2 Test for unused element in a loop 3 Assignment of values to arrays // save index of first blank location and assign after loop 4 Set loop termination if empty element found in a loop 5 Call SortArrays() once 6 Calculation of remaining unused elements and return Integer value (for both cases) FUNCTION AddError(ErrNum : INTEGER, ErrMess : STRING) RETURNS INTEGER DECLARE Index, Remaining : INTEGER CONSTANT Unused = 999 Index 1 Remaining -1 REPEAT IF ErrCode[Index] = Unused THEN ErrCode[Index] ErrNum ErrText[Index] ErrMess CALL SortArrays() Remaining 500 – Index ENDIF Index Index + 1 UNTIL Remaining <> -1 OR Index > 500 RETURN Remaining ENDFUNCTION 7(b)(ii) One mark per point (Max 3): 3 1. Loop through 500 elements (while error number not found) 2. Compare ErrCode for current element with the error number 3. If same, set element value to 999 (and terminate loop) 4. ... and call SortArrays() (to move 999 to the end) – once only
4 Function Replace() will: 1. take three parameters: • a string (the original string) • a char (the original character) • a char (the new character) 2. form a new string from the original string where all instances of the original character are replaced by the new character 3. return the new string. Write pseudocode for function Replace(). … … … … … … … … … … … … … … … … … … [6]
6 marks
Mark scheme: 4 Function Replace(OldString : STRING, Char1, Char2 : 6 CHAR) __ RETURNS : STRING DECLARE NewString : STRING DECLARE ThisChar : CHAR DECLARE Index : INTEGER NewString "" FOR Index 1 TO LENGTH(OldString) ThisChar MID(OldString, Index, 1) IF ThisChar = Char1 THEN ThisChar Char2 ENDIF NewString NewString & ThisChar NEXT Index RETURN NewString ENDFUNCTION Mark as follows: 1 Function heading and ending, including parameters and return type 2 Declaration of local variables used including loop counter 3 Loop for length of OldString 4 Extract char and test in a loop 5 Use of concatenate to build NewString replace char if necessary, in a loop 6 Return NewString after reasonable attempt
8 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> Item information is as follows: Format Comment unique for each item in the range ItemNum 4 numeric characters "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() • called with a parameter of type string representing a supplier code (already written) • returns TRUE if the supplier code is already in use, otherwise returns FALSE IsNewSupp() • called with a parameter of type string representing a new supplier code • returns TRUE if the string only contains alphabetic characters (either upper or lower case) and the supplier code is not already in use, otherwise returns FALSE (a) Write pseudocode for module IsNewSupp(). 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. … … … … … … … … … … … … … … … … … … … … … … … [7] (b) A new module has been defined: 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 already exists in the file • returns TRUE if the ItemNum is not already in the file, otherwise returns FALSE Write efficient pseudocode for module CheckNewItem(). … … … … … … … … … … … … … … … … … … … … …
7 marks
Mark scheme: 8(a) FUNCTION IsNewSupp(ThisString : STRING) RETURNS BOOLEAN 7 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 ThisString is exactly 5 characters in length 2 Use of SuppExists() with a string of 5 characters as a parameter 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 8(b) FUNCTION CheckNewItem(NewLine : STRING) RETURNS BOOLEAN 7 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 Stock.txt in READ mode and subsequently close 2 Extract NewItemNum from parameter 3 Conditional loop until EOF("Stock.txt") 4 ... OR NewItemNum found 5 ... OR when ThisItemNum < NewItemNum 6 Read a line from Stock.txt AND extract ThisItemNum in a loop 7 If ThisItemNum = NewItemNum then terminate loop / set flag in 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) Integration testing 1 8(c)(ii) Two marks for the description: 2 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) Append 1 8(e) One mark for each part: 3 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
1 A program calculates the postal cost based on the weight of the item and its destination. Calculations occur at various points in the program and these result in the choice of several possible postal costs. The programmer has built these postal costs into the program. For example, the postal cost of $3.75 is used in the following lines of pseudocode: IF Weight < 250 AND ValidAddress = TRUE THEN ItemPostalCost 3.75 // set postal cost for item to $3.75 ItemStatus "Valid" // item can be sent ENDIF (a) (i) Identify a more appropriate way of representing the postal costs. … [1] (ii) Describe the advantages of your answer to part (a)(i) with reference to this program. … … … … … … [3] (b) The lines of pseudocode contain features that make them easier to understand. State three of these features. 1 … 2 … 3 … [3] (c) Give the appropriate data types for the following variables: ValidAddress … ItemPostalCost … ItemStatus … [3]
10 marks
Mark scheme: Question Answer Marks 1(a)(i) Use of constants 1 1(a)(ii) One mark per bullet point (or equivalent to max 3): 3 1 Postal rates are entered once only 2 Avoids input error / changing the cost accidentally // avoids different values for postal rates at different points in the program 3 When required, the constant representing the postal rate value is changed once only // easier to maintain the program when the postal rates change 4 Makes the program easier to understand Note: Max 3 marks 1(b) One mark per bullet point: 3 Indentation White space Comments Sensible / meaningful variable names // use of Camel Case Capitalised keywords Note: Max 3 marks 1(c) One mark per bullet point: 3 BOOLEAN REAL STRING
5 A programmer has produced the following pseudocode to output the square root of the numbers from 1 to 10. Line numbers are for reference only. 10 DECLARE Num : REAL 11 Num 1.0 ... 40 REPEAT 41 CALL DisplaySqrt(Num) 42 Num Num + 1.0 43 UNTIL Num > 10 ... 50 PROCEDURE DisplaySqrt(BYREF ThisNum : REAL) 51 OUTPUT ThisNum 52 ThisNum SQRT(ThisNum) // SQRT returns the square root 53 OUTPUT " has a square root of ", ThisNum 54 ENDPROCEDURE The pseudocode is correctly converted into program code. Function SQRT() is a library function and contains no errors. The program code compiles without errors, but the program gives unexpected results. These are caused by a design error. (a) Explain why the program gives unexpected results. … … … … … … [3] (b) Explain why the compiler does not identify this error. … … [1] (c) Describe how a typical Integrated Development Environment (IDE) could be used to identify this error. … … … … … … [3] (d) The pseudocode is converted into program code as part of a larger program. During compilation, a complex statement generates an error. The programmer does not want to delete the complex statement but wants to change the statement so that it is ignored by the compiler. State how this may be achieved. … … [1]
8 marks
Mark scheme: 5(a) One mark per point: 3 parameter / Num has been passed by reference // should have been passed by value so when the value / ThisNum is modified (in procedure DisplaySqrt()) the new value will be used in the loop (lines 40–43) // Num will be changed to modified value 5(b) The rules of the language have not been broken // there are no syntax 1 errors 5(c) Could use an IDE to: 3 Set a breakpoint to stop the program at a certain line / statement / point Step through the program line by line / statement by statement checking the value of 'num' / a variable using a report / watch window One mark per bullet 5(d) Answers include: 1 Change the statement into a comment Change the statement to a string representing a literal value and assign it to a variable / output it Note: max 1 mark
6 A procedure Select() will: 1. take two integer values as parameters representing start and end values where both values are greater than 9 and the end value is greater than the start value 2. output each integer value between the start and the end value (not including the start and end values), where the sum of the last two digits is 6, for example, 142. (a) Write pseudocode for procedure Select(). Parameter validation is not required. … … … … … … … … … … … … … … … … … … … … … … … [7] (b) The check performed by procedure Select() on the last two digits is needed at several places in the program and will be implemented using a new function. The new function CheckNum() will: • allow the required sum to be specified (not just 6) • check one number • return an appropriate value. Describe the function interface and two advantages of this modular approach. Interface … … … … Advantage 1 … … Advantage 2 … … [4]
11 marks
Mark scheme: 6(a) Max 7 marks 7 PROCEDURE Select(Start, End : INTEGER) DECLARE ThisNum, Total: INTEGER DECLARE ThisString : STRING DECLARE Char1, Char2 : CHAR FOR ThisNum Start+1 TO End-1 ThisString NUM_TO_STR(ThisNum) Char1 RIGHT(ThisString, 1) Char2 LEFT(RIGHT(ThisString, 2), 1) Total STR_TO_NUM(Char1) + STR_TO_NUM(Char2) IF Total = 6 THEN OUTPUT ThisString ENDIF NEXT ThisNum ENDPROCEDURE MP1 Procedure heading and ending MP2 (Count-controlled) Loop MP3 …. with correct range from Start+1 to End-1 MP4 Convert ThisNum (loop counter) to a string MP5 Extract the last two/first/second ’character digit(s)’ required in a loop MP6 Extract the second individual ‘character digit’ required in a loop MP7 Calculate the sum of the last two digits MP8 If sum = 6 then OUTPUT the number (either string or integer) in a loop 6(b) Max 4 marks 4 MP1 The function will take two integer parameters - the number and the (required) total MP2 … and return a Boolean OR: CheckNum(Number,Total : INTEGER) RETURNS BOOLEAN MP1 MP2 Two marks for the advantages: MP3 CheckNum()can be called repeatedly as and when required MP4 CheckNum()is designed and tested once (then used repeatedly) MP5 Any subsequent change to CheckNum() needs to be made once only // is easier to maintain/modify