Worked solution from the Data Types and Structures Paper 2 Problem-solving and Programming booklet, Part 3 of 4.
Check the length first. Then compare the first 9 or 10 characters (in upper case) with the keyword and a space. If it matches, return the letter and the rest of the line.
FUNCTION Header(Line : STRING) RETURNS STRING
IF LENGTH(Line) >= 13 THEN
IF TO_UPPER(LEFT(Line, 9)) = "FUNCTION " THEN
RETURN "F" & RIGHT(Line, LENGTH(Line) - 9)
ENDIF
IF TO_UPPER(LEFT(Line, 10)) = "PROCEDURE " THEN
RETURN "P" & RIGHT(Line, LENGTH(Line) - 10)
ENDIF
ENDIF
RETURN ""
ENDFUNCTIONFunction heading, parameter, return type and ending [1]
Checks that the line is at least 13 characters before extracting, and returns an empty string otherwise [1]
Attempts to extract 9 or 10 characters (keyword plus space) and compare with the keyword plus space [1]
The extract and compare is completely correct [1]
Uses case conversion (TO_UPPER or TO_LOWER) so any case is accepted [1]
Works out the rest of the line and joins it to "P" or "F" [1]
Returns the string [1]
Read the file line by line and keep a line number. Call Header() on each line. If it is not empty, store the line number, the letter and the description in the next row of ModInfo.
PROCEDURE FindModules(FileName : STRING)
DECLARE Line : STRING
DECLARE Index, LineNum : INTEGER
OPENFILE FileName FOR READ
Index ← 1
LineNum ← 0
WHILE NOT EOF(FileName)
READFILE FileName, Line
LineNum ← LineNum + 1
Line ← Header(Line)
IF Line <> "" THEN
ModInfo[Index, 1] ← NUM_TO_STR(LineNum)
ModInfo[Index, 2] ← LEFT(Line, 1)
ModInfo[Index, 3] ← RIGHT(Line, LENGTH(Line) - 1)
Index ← Index + 1
ENDIF
ENDWHILE
CLOSEFILE FileName
ENDPROCEDUREFile opened in READ mode and closed afterwards [1]
Loop that runs until EOF [1]
Reads a line and keeps the line number up to date inside the loop [1]
Calls Header() and uses the value it returns inside the loop [1]
Tests the returned value for an empty string inside the loop [1]
Attempts to assign all three columns of the correct row [1]
Correct values go into all three columns (line number as a string, the letter, the description) [1]
The row index is increased only when a module is found [1]
▶ Starts at Q8 (1:12:59)
Starts at Q8 (1:12:59) · by Pseudocode Pro. Tap the picture to open it on YouTube.
Solutions follow the official Cambridge mark schemes; marks are shown in grey. Videos are from other YouTube channels. Paper codes read component / series / year: M/J = May/June, O/N = October/November. Past-paper questions © UCLES, reproduced for classroom practice.