Worked solution from the Data Types and Structures Paper 2 Problem-solving and Programming booklet, Part 3 of 4.
Give a reason and a benefit:
Reason: the program is easier to design, test, debug or modify in separate stages [1]
Benefit: it is easier to check that each stage works as expected by looking at its own file [1]
Find the position of the first character that is not a space. Then keep the rest of the line from that point.
FUNCTION DeleteSpaces(Line : STRING) RETURNS STRING
DECLARE NewLine : STRING
DECLARE EndOfLeading : BOOLEAN
DECLARE Count, NumSpaces : INTEGER
DECLARE NextChar : CHAR
CONSTANT Space = " "
NumSpaces ← 0
EndOfLeading ← FALSE
FOR Count ← 1 TO LENGTH(Line)
NextChar ← MID(Line, Count, 1)
IF NextChar <> Space AND EndOfLeading = FALSE THEN
NumSpaces ← Count - 1
EndOfLeading ← TRUE
ENDIF
NEXT Count
NewLine ← RIGHT(Line, LENGTH(Line) - NumSpaces)
RETURN NewLine
ENDFUNCTIONLoop through the length of Line (or until the first non-space) [1]
Extracts a character inside the loop [1]
Identifies the first non-space character inside the loop [1]
Attempts to remove the leading spaces from Line [1]
The leading spaces are removed correctly (a new string without them) [1]
Returns the string after a reasonable attempt [1]
Clean each line with both modules. Write it only if it is not empty. Otherwise count it as a blank line.
PROCEDURE Stage_2(F1, F2 : STRING)
DECLARE Line : STRING
DECLARE Count : INTEGER
Count ← 0
OPENFILE F1 FOR READ
OPENFILE F2 FOR APPEND
WHILE NOT EOF(F1)
READFILE F1, Line
Line ← DeleteSpaces(Line)
Line ← DeleteComment(Line)
IF Line <> "" THEN
WRITEFILE F2, Line
ELSE
Count ← Count + 1
ENDIF
ENDWHILE
CLOSEFILE F1
CLOSEFILE F2
OUTPUT Count, " blank lines were removed"
ENDPROCEDUREProcedure heading, parameters and ending [1]
Both files opened in the correct modes (F1 for read, F2 for append because it already exists) and closed afterwards [1]
Loop that runs until EOF(F1) [1]
Reads a line from F1 inside the loop [1]
Assigns the values returned by DeleteComment() and DeleteSpaces() inside the loop [1]
Checks the result is not empty and, if so, writes it to F2 inside the loop [1]
Counts the blank lines inside the loop [1]
Outputs the number of blank lines removed after the loop [1]
▶ Starts at Q8 (1:12:50)
Starts at Q8 (1:12:50) · 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.