Worked solution from the Data Types and Structures Paper 2 Problem-solving and Programming booklet, Part 3 of 4.
Look for "//" by taking two characters at a time. Stop at the first one, remember where it starts, and keep only the text before it.
FUNCTION DeleteComment(Line : STRING) RETURNS STRING
DECLARE NewLine, TwoChars : STRING
DECLARE Count, TrimTo : INTEGER
CONSTANT Comment = "//"
NewLine ← Line
TrimTo ← 0
Count ← 1
WHILE Count < LENGTH(Line) AND TrimTo = 0
TwoChars ← MID(Line, Count, 2)
IF TwoChars = Comment THEN
TrimTo ← Count
ENDIF
Count ← Count + 1
ENDWHILE
IF TrimTo <> 0 THEN
NewLine ← LEFT(Line, TrimTo - 1)
ENDIF
RETURN NewLine
ENDFUNCTIONLoop that goes up to the length of Line [1]
Loop stops at the first double slash [1]
Extracts one or two characters inside the loop [1]
Checks for "//" after extracting, inside the loop [1]
Records the start position of the comment (or the amount to trim) [1]
Attempts to trim Line from the start of the comment [1]
The trimmed line is completely correct (everything before the comment) [1]
Returns the line [1]
Build the two file names, read each line, remove the comment with DeleteComment(), then write only the lines that are not empty. Count the lines written.
FUNCTION Stage_1(StudentName : STRING) RETURNS INTEGER
DECLARE OldFile, NewFile, Line : STRING
DECLARE Count : INTEGER
OldFile ← StudentName & "_src.txt"
NewFile ← StudentName & "_S1.txt"
OPENFILE OldFile FOR READ
OPENFILE NewFile FOR WRITE
Count ← 0
WHILE NOT EOF(OldFile)
READFILE OldFile, Line
Line ← DeleteComment(Line)
IF LENGTH(Line) <> 0 THEN
WRITEFILE NewFile, Line
Count ← Count + 1
ENDIF
ENDWHILE
CLOSEFILE OldFile
CLOSEFILE NewFile
RETURN Count
ENDFUNCTIONBoth file names made from StudentName (a missing underscore is forgiven) [1]
Both files opened in the correct modes (READ and WRITE) and closed afterwards [1]
Loop that runs until EOF of the project file [1]
Reads a line and calls DeleteComment() inside the loop [1]
Skips blank lines after DeleteComment() inside the loop [1]
Writes the line to the stage 1 file and adds 1 to Count inside the loop [1]
Returns the number of lines written [1]
▶ Starts at Q8 (1:19:38)
Starts at Q8 (1:19:38) · 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.