Skip to content

10.3 Files

AS Level · 7 questions found

  • Why files are needed for persistent storage
  • Write pseudocode to handle text files with one or more lines
Q8
May/Jun 2024 Paper 2 v1 7 marks
Question 8
8
Show mark scheme
8(a) [7 marks]
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) // extract 2 chars
IF TwoChars = Comment THEN

TrimTo
Count
ENDIF

Count
Count + 1
ENDWHILE
IF TrimTo <> 0 THEN

NewLine
LEFT(Line, TrimTo - 1)
ENDIF
RETURN NewLine
ENDFUNCTION
Mark as follows:
1
Loop to length of
(parameter) // length of
Line
Line -1
2
Terminate loop on first double slash
3
Attempt to extract one/two characters
in a loop
4
Check for "//" after attempt at extraction
in a loop
5
Record start position of comment // Calculate amount of trim required
6
Attempt to trim
from start of comment
Line
7
Completely correct trimmed
from start of comment
Line
8
Return
after a reasonable overall attempt
Line
8(b)
Example:
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
ENDFUNCTION
Mark as follows:
1
Generate filenames condone missing “_”
2
Open both files in correct modes
and
subsequently close
3
Loop to
EOF(OldFile)
4
Read a line from
and
execute
in a loop
OldFile
DeleteComment()
5
Skip blank lines after
in a loop
DeleteComment()
6
Write
to stage 1 file
and
increment Count
Line
7
Return the number of lines after a reasonable attempt at counting
Q3
May/Jun 2024 Paper 2 v2 10 marks
Question 3 — page 1Question 3 — page 2
3 A factory needs a program to help manage its production of items. Data will be stored about each item. The data for each item will be held in a record structure of type Component. The programmer has started to define the fields that will be needed as shown in the table. Field Example value Comment Item_Num 123478 a numeric value used as an array index Reject FALSE TRUE if this item has been rejected Stage 'B' a letter to indicate the stage of production Limit_1 13.5 any value in the range 0 to 100 inclusive Limit_2 26.4 any value in the range 0 to 100 inclusive (a) (i) Write pseudocode to declare the record structure for type Component. ..................................................................................................................................... [4] (ii) A 1D array Item of 2000 elements will store the data for all items. Write pseudocode to declare the Item array. ..................................................................................................................................... [2] (b) State three benefits of using an array of records to store the data for all items. 1 ................................................................................................................................................ 2 ................................................................................................................................................ 3 ................................................................................................................................................ [3]
Show mark scheme
3(a)(i) [2 marks]
Pseudocode:
TYPE Component
DECLARE Item_Num : INTEGER
DECLARE Reject : BOOLEAN
DECLARE Stage : CHAR
DECLARE Limit_1 : REAL
DECLARE Limit_2 : REAL
ENDTYPE
Mark as follows:
1
One mark for
and
statements
TYPE
ENDTYPE
2
One mark for
and
fields
Item_Num
Reject
3
One mark for
field
Stage
4
One mark for Limit fields as
REAL
DECLARE Item : ARRAY [1:2000] OF Component//
3(a)(ii) [3 marks]
DECLARE Item : ARRAY [2000] OF Component//
DECLARE Item : ARRAY [0:1999] OF Component
One mark per underlined phrase
3(b) [5 marks]
One mark per point:
1
Allows for iteration / can use a loop
to access the records / data items
2
Use of index to directly access a
record
in the array // Example of
simplification of code e.g. use of dot notation Item[1].Stage
3
Simplifies the code / algorithm // Reduces duplication of code //
Program
easier to write / understand / maintain / test / debug //
Data items/record
easier to search / sort / manipulate
Q7
May/Jun 2024 Paper 2 v2 7 marks
Question 7 — page 1Question 7 — page 2Question 7 — page 3
7 A fitness club has a computerised membership system. The system stores information for each club member: name, home address, email address, mobile phone number, date of birth and exercise preferences. Many classes are full, and the club creates a waiting list for each class. The club adds details of members who want to join a class that is full to the waiting list for that class. When the system identifies that a space is available in one of the classes, a new module will send a text message to each member who is on the waiting list. (a) Decomposition will be used to break the new module into sub‑modules (sub‑problems). Identify three sub‑modules that could be used in the design and describe their use. Sub‑module 1 ........................................................................................................................... Use ........................................................................................................................................... Sub‑module 2 ........................................................................................................................... Use ........................................................................................................................................... Sub‑module 3 ........................................................................................................................... Use ........................................................................................................................................... [3] (b) A different part of the program is represented by the following state‑transition diagram. S1 START S4 S3 Input-B | Output-W Input-A | Output-X Input-B | Output-Y Input-A | Output-W Input-B Input-B Input-A Input-A S2 S5 (i) Complete the table to show the inputs, outputs and next states. Assume that the current state for each row is given by the ‘Next state’ on the previous row. For example, the first Input‑A is made when in state S1. If there is no output for a given transition, then the output cell should contain ‘none’. The first two rows have been completed. Input Output Next state S1 Input‑A none S3 Output‑W none Input‑B Input‑A S4 [5] (ii) Identify the input sequence that will cause the minimum number of state changes in the transition from S1 to S4. ..................................................................................................................................... [1]
Show mark scheme
7(a)
Examples include:
Module:
IdentifyMember()
Use: Identifies a club member who has expressed an interest in a given class
Module:
GetMemberPhoneNumber()
Use: Gets the mobile phone number of a member
Module:
CreateMessage()
Use: Generates a text message to a member
Module:
SendMessage()
Use: Sends a text message to a member in the waiting list
One mark for name
and
use
Note: max 3 marks
7(b)(i) [5 marks]
Input
Output
Next state
S1
Input-A
none
S3
Input-A
Output-W
S3
Input-B
none
S2
Input-B
none
S5
Input-A
none
S2
Input-A
Output-X
S4
One mark per row 3 to 7
7(b)(ii) [2 marks]
Input-B, Input-A
Q8
May/Jun 2024 Paper 2 v2 14 marks
Question 8 — page 1Question 8 — page 2Question 8 — page 3Question 8 — page 4Question 8 — page 5Question 8 — page 6Question 8 — page 7
8 A teacher is designing a program to process pseudocode projects written by her students. Each student project is stored in a text file. The process is split into a number of stages. Each stage performs a different task and creates a new file. For example: File name Comment MichaelAday_src.txt Student project file produced by student Michael Aday MichaelAday_S1.txt File produced by stage 1 MichaelAday_S2.txt File produced by stage 2 (a) Suggest a reason why the teacher’s program has been split into a number of stages and give the benefit of producing a different file from each stage. Reason ..................................................................................................................................... Benefit ...................................................................................................................................... [2] (b) The teacher has defined the first program module as follows: Module Description DeleteSpaces() • called with a parameter of type string representing a line of pseudocode from a student’s project file • returns the line after removing any leading space characters The following example shows a string before and after the leading spaces have been removed: Before: " IF X2 > 13 THEN" After: "IF X2 > 13 THEN" Complete the pseudocode for module DeleteSpaces(). FUNCTION DeleteSpaces(Line : STRING) RETURNS STRING ENDFUNCTION [6] (c) Two modules are defined: Module Description DeleteComment() (already written) • called with a parameter of type string representing a line of pseudocode from a student’s project file • returns the line after removing any comment Stage_2() • called with two parameters: ○ a string representing an input file name ○ a string representing an output file name • copies each line from the input file to the existing output file having first removed all leading spaces and comments from that line • does not write blank lines to the output file • outputs a final message giving the number of blank lines removed Write pseudocode for module Stage_2(). Modules DeleteComment() and DeleteSpaces() must be used in your solution. ............................................................................................................................................. [8] BLANK PAGE BLANK PAGE Permission to reproduce items where third‑party owned material protected by copyright is included has been sought and cleared where possible. Every reasonable effort has been made by the publisher (UCLES) to trace copyright holders, but if any items requiring clearance have unwittingly been included, the publisher will be pleased to make amends at the earliest possible opportunity. To avoid the issue of disclosure of answer‑related information to candidates, all copyright acknowledgements are reproduced online in the Cambridge Assessment International Education Copyright Acknowledgements Booklet. This is produced for each series of examinations and is freely available to download at www.cambridgeinternational.org after the live examination series. Cambridge Assessment International Education is part of Cambridge Assessment. Cambridge Assessment is the brand name of the University of Cambridge BLANK PAGE
Show mark scheme
8(a) [6 marks]
One mark for reason, one for benefit
Reason: (Program is) easier to design / implement / test / debug / modify
Benefit: Easier to check that
each stage
works as expected
8(b) [8 marks]
Example algorithm based on finding position of first non-space character and
then using substring function:
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 // the number to trim
EndOfLeading = TRUE
ENDIF
NEXT Count

NewLine
RIGHT(Line, LENGTH(Line) - NumSpaces)
RETURN NewLine
ENDFUNCTION
Mark as follows:
1
Loop to length of parameter
// Loop until first non-space
character in Line
2
Extract a character
in a loop
3
Identify first non-space character
in a loop
4
Attempt at removing leading spaces in
Line
5
Leading spaces removed from
/ / Create new string without leading
Line
space
6
Return a string following a reasonable attempt at removing leading spaces
in
Line
8(c)
Example:
PROCEDURE Stage_2(F1, F2 : STRING)
DECLARE Line : STRING
DECLARE Count : INTEGER

Count
0
OPEN F1 FOR READ
OPEN F2 FOR APPEND
WHILE NOT EOF(F1)
READFILE F1, Line

Line
DeleteSpaces(Line)

Line
DeleteComment(Line)
IF Line <> "" THEN
WRITEFILE F2, Line // skip blank lines
ELSE

Count
Count + 1
ENDIF
ENDWHILE
CLOSEFILE F1
CLOSEFILE F2
OUTPUT Count, " blank lines were removed"
ENDPROCEDURE
Mark as follows:
1
Procedure heading, parameters, ending
2
Open both files in correct modes
and
subsequently close
3
Loop to
EOF(F1)
4
Read a line from
in a loop
F1
5
Assign return values from
and
DeleteComment()
DeleteSpaces()
in a loop
6
Check return value following both MP5 function calls is not an empty
string and if so write to
in a loop
F2
7
Count the blank lines
in a loop
8
Output number of blank lines removed following a reasonable attempt
after the loop
Q2
May/Jun 2024 Paper 2 v3 3 marks
Question 2 — page 1Question 2 — page 2Question 2 — page 3
2 (a) A program uses a global 1D array of type string and a text file. An algorithm that forms part of the program is expressed as follows: • copy the first line from the file into the first element of the array • copy the second line from the file into the second element of the array • continue until all lines in the file have been copied into the array. Stepwise refinement is applied to the algorithm. Outline five steps for this algorithm that could be used to produce pseudocode. Assume there are more elements in the array than lines in the file. Do not use pseudocode statements in your answer. Step 1 ....................................................................................................................................... Step 2 ....................................................................................................................................... Step 3 ....................................................................................................................................... Step 4 ....................................................................................................................................... Step 5 ....................................................................................................................................... [5] (b) Sequence 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 its use. Construct .................................................................................................................................. Use ........................................................................................................................................... [2] BLANK PAGE ,  , ,  ,
Show mark scheme
2(a)
One mark per point:
1. Open the file (in read mode and subsequently close)
2. Initialise an index variable (to 1 // 0)
3. Repeat (the next three steps) until the end of file is reached
4. Read a line from the file (into a string variable)
5. Store the line / variable in the array at the index
6. Increment the index
in a loop
Note: max 5 marks
2(b) [3 marks]
One mark per point:
Construct: a conditional loop
Use: To keep repeating until the
end of the file is reached
ALTERNATIVE:
Construct: a selection statement
Use: To test / check the value returned by the
function
EOF()
Q8
May/Jun 2024 Paper 2 v3 8 marks
Question 8 — page 1Question 8 — page 2Question 8 — page 3Question 8 — page 4Question 8 — page 5Question 8 — page 6Question 8 — page 7
8 A teacher is designing a program to process pseudocode projects written by her students. The program analyses a student project and extracts information about each module that is defined (each procedure or function). This information is stored in a global 2D array ModInfo of type string. A module header is the first line of a module definition and starts with either of the keywords PROCEDURE or FUNCTION. An example of part of the array is given below. Row 10 of the array shows that a procedure header occurs on line 27 and row 11 shows that a function header occurs on line 35. "P" represents a procedure and "F" represents a function: x = 1 x = 2 x = 3 ModInfo[10, x] "27" "P" "MyProc(Z : CHAR)" ModInfo[11, x] "35" "F" "MyFun(Y : CHAR) RETURNS BOOLEAN" The string stored in column 3 is called the module description. This is the module header without the keyword. A valid module header will: • be at least 13 characters long • start with the keyword PROCEDURE or FUNCTION. The keyword may appear in either upper or lower case (or a mix of both) and must be followed by a space character. The teacher has defined the first program module as follows: Module Description Header() • called with a parameter of type string representing a line of pseudocode • if the line is a valid procedure header, returns a string: "P<Module description>" • if the line is a valid function header, returns a string: "F<Module description>" • otherwise, returns an empty string For example, given the string: "FUNCTION Zap(X : INTEGER) RETURNS CHAR" Header()returns the string: "FZap(X : INTEGER) RETURNS CHAR" (a) Write pseudocode for module Header(). ............................................................................................................................................. [7] ,   , (b) A new module is required: Module Description FindModules() • called with a parameter of type string representing a student project file name • uses module Header() to check each line of the project • assigns values to the ModInfo array for each module declaration in the student project As a reminder, the previous example of part of the array is repeated below: x = 1 x = 2 x = 3 ModInfo[10, x] "27" "P" "MyProc(Z : CHAR)" ModInfo[11, x] "35" "F" "MyFun(Y : CHAR) RETURNS BOOLEAN" Write pseudocode for module FindModules(). Assume that the array contains enough rows for the number of modules in each project. ,  , ............................................................................................................................................. [8] ,  , BLANK PAGE ,  , BLANK PAGE ,  , Permission to reproduce items where third-party owned material protected by copyright is included has been sought and cleared where possible. Every reasonable effort has been made by the publisher (UCLES) to trace copyright holders, but if any items requiring clearance have unwittingly been included, the publisher will be pleased to make amends at the earliest possible opportunity. To avoid the issue of disclosure of answer-related information to candidates, all copyright acknowledgements are reproduced online in the Cambridge Assessment International Education Copyright Acknowledgements Booklet. This is produced for each series of examinations and is freely available to download at www.cambridgeinternational.org after the live examination series. BLANK PAGE ,  ,
Show mark scheme
8(a) [8 marks]
Example:
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 ""
ENDFUNCTION
Mark as follows:
1
Function heading, parameter, return type and ending
2
Check that the line is at least 13 characters long before attempting to
extract and return empty string
3
Attempt at: Extract characters, 9 or 10 characters, corresponding to
keyword plus space and compare with appropriate keyword plus space
4
Completely correct MP3
Use of type case conversion to allow for 'any case'
5
6
Calculation of 'rest of line' and concatenation with 'P or 'F'
7
Return string
8(b)
Example:
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
ENDPROCEDURE
Mark as follows:
1
Open file in
mode
and
subsequently close
READ
2
Loop to
EOF(FileName)
3
Read a line from the file and maintain
in
a loop
LineNum
4
Call
and use return value
in a loop
Header()
5
Test return value for ""
in a loop
6
Attempt at all three-array assignment for all columns in correct row
7
Correct values assigned to all columns of array
8
Maintain correct array row index
Q1
May/Jun 2024 Paper 4 v2 2 marks
Question 1 — page 1Question 1 — page 2Question 1 — page 3Question 1 — page 4Question 1 — page 5
1 A program outputs a main word. The program asks the user to enter the different words of 3 or more letters that can be made from the letters in the main word. These are called the answers. There are 3 files: Easy.txt, Medium.txt and Hard.txt. Each file has the main word on the first line. For example, the main word in Easy.txt is house. The answers are stored in the file. Each answer is on a new line after the main word. For example, Easy.txt has 14 answers that can be made from the letters in house. The words read from the text file are stored in the global array WordArray. The number of words that can be made from the letters in the main word is stored in the global variable NumberWords. (a) The procedure ReadWords(): • takes a file name as a parameter • opens the file and reads in the data • stores the main word in the first element in WordArray • stores each answer in a new element in WordArray • counts and stores the number of answers. Write program code for the procedure ReadWords(). Save your program as Question1_J24. Copy and paste the program code into part 1(a) in the evidence document. [6] (b) The main program asks the user to enter "easy", "medium" or "hard" and calls ReadWords()with the filename that matches the user’s input. For example, if the user enters "easy", the parameter is "Easy.txt". Write program code for the main program. Save your program. Copy and paste the program code into part 1(b) in the evidence document. [4] (c) (i) The procedure Play(): • outputs the main word from the array and the number of answers • allows the user to enter words until they enter the word ‘no’ to indicate they want to stop • outputs whether each word the user enters is an answer or not an answer • counts the number of answers the user gets correct • replaces each answer that the user gets correct with a null value in the array. Write program code for the procedure Play(). Save your program. Copy and paste the program code into part 1(c)(i) in the evidence document. [6] (ii) Amend the procedure Play()so that when the user enters the command to stop, the procedure: • outputs the percentage of answers the user entered from the array • outputs all the answers that the user did not enter. Write program code to amend Play(). Save your program. Copy and paste the program code into part 1(c)(ii) in the evidence document. [3] (d) (i) The procedure ReadWords()calls Play()after the data in the file has been read. Write program code to amend ReadWords(). Save your program. Copy and paste the program code into part 1(d)(i) in the evidence document. [1] (ii) Test your program by inputting these words in the order shown: easy she out no Take a screenshot of the output(s). Save your program. Copy and paste the screenshot into part 1(d)(ii) in the evidence document. [1] (iii) Test your program by inputting these words in the order shown: hard fine fined idea no Take a screenshot of the output(s). Save your program. Copy and paste the screenshot into part 1(d)(iii) in the evidence document. [1] BLANK PAGE
Show mark scheme
1(a)
}catch(FileNotFoundException e){
System.out.println("File not found");
VB.NET
Sub ReadWords(FileName As String)
Try
Dim DataReader As StreamReader = New StreamReader(FileName)
NumberWords = 0
Do Until DataReader.EndOfStream
WordArray(NumberWords) = DataReader.ReadLine()
NumberWords = NumberWords + 1
Loop
DataReader.Close()
Catch ex As Exception
Console.WriteLine("Invalid file")
End Try
End Sub
Python
def ReadWords(FileName):
global WordArray
global NumberWords
File = open(FileName, 'r')
DataRead = File.read().strip()
File.close()
WordArray = DataRead.split()
NumberWords = len(WordArray)
1(b)
FileName = "Hard.txt"
End If
ReadWords(FileName)
End Sub
Python
WordArray = []
NumberWords = 0
Choice = input("Easy, medium or hard? ").lower()
if Choice == "easy":
File = "Easy.txt"
elif Choice == "medium":
File = "Medium.txt"
else:
File = "Hard.txt"
ReadWords(File)
1(c)(i)
for x in range(0, NumberWords):
WordArray[x] = ""
QuantityFound = QuantityFound + 1
print("Correct, you have found", QuantityFound, "words")
Found = True
if Found == False:
print("Sorry that was incorrect")
1(c)(ii)
if Correct < 100:
print("The words you missed are")
for x in range(0, NumberWords-1):
if WordArray[x] != "":
print(WordArray[x])
1(d)(i)
VB.NET
Sub ReadWords(FileName As String)
Try
Dim DataReader As StreamReader = New StreamReader(FileName)
NumberWords = 0
Do Until DataReader.EndOfStream
WordArray(NumberWords) = DataReader.ReadLine()
NumberWords = NumberWords + 1
Loop
DataReader.Close()
Play()
Catch ex As Exception
Console.WriteLine("Invalid file")
End Try
End Sub
Python
def ReadWords(FileName):
global WordArray
global NumberWords
File = open(FileName, 'r')
DataRead = File.read().strip()
File.close()
WordArray = DataRead.split()
NumberWords = len(WordArray)
Play()
1(d)(ii) [1 mark]
1 mark for screenshot showing the inputs "easy", "she", "out", "no" e.g.
1(d)(iii) [1 mark]
1 mark for screenshot showing the inputs ‘hard’, ‘fine’, ‘fined’, ‘idea’, ‘no’ e.g.