Get matched

File processing, classes and exceptions

Start questions

AI-assisted English content review; independent teacher approval pending.

Practice scope and review

Original, AI-authored English practice with worked guidance. Selected topics only; independent teacher review is pending. This is not a complete syllabus, official past-paper collection or predicted exam score. Check your own exam-board specification: these concepts are not certified against a particular board or exam year.

151 original questions across 21 selected topic areas. No account or payment required to practise.

Cambridge International AS & A Level Computer Science (9618), examination year 2027: AI-assisted conceptual alignment to official sources, not teacher or exam-board certification. Syllabus mapping and remaining coverage.

5 questions in this topic

Exact English revisions checked in an AI-assisted academic review; independent teacher approval is still pending.

All topics

Original English exercises targeting selected 9618 2027-29 requirements. Conceptual alignment only; independent teacher approval, practical competence and complete teaching coverage are not established.

Subtopics in this topic (4)
  • EOF-safe text processing
  • Keyed random records
  • Inheritance and encapsulation
  • Exceptions and input errors

5 of 5 questions shown

Loading saved responses

Question 1Write Cambridge pseudocode to copy nonempty lines from Input.txt to Clean.txt, replacing any old Clean.txt. Input contains three lines: A, an empty line, BC. State final output and number of READFILE operations; also trace an empty input file and explain why APPEND would violate the replacement requirement.6 indicative marks

Write Cambridge pseudocode to copy nonempty lines from Input.txt to Clean.txt, replacing any old Clean.txt. Input contains three lines: A, an empty line, BC. State final output and number of READFILE operations; also trace an empty input file and explain why APPEND would violate the replacement requirement.

Show indicative guidance

Worked guidance

  1. DECLARE Line : STRING
    OPENFILE "Input.txt" FOR READ
    OPENFILE "Clean.txt" FOR WRITE
    WHILE NOT EOF("Input.txt")
       READFILE "Input.txt", Line
       IF Line <> "" THEN
          WRITEFILE "Clean.txt", Line
       ENDIF
    ENDWHILE
    CLOSEFILE "Input.txt"
    CLOSEFILE "Clean.txt"
  2. The three reads yield A, empty, BC. Only A and BC are written, in that order. For an empty input, EOF is already TRUE, so no attempted read occurs. A post-condition loop would try an invalid first read unless separately guarded.
  3. WRITE creates or truncates the output, removing OLD content; APPEND would produce OLD,A,BC. READFILE returns text lines as STRING. Actual file permissions, media errors and practical testing remain part of teacher-led work.

Self-marking points

View marking points
  1. Open input FOR READ and output FOR WRITE.
  2. Declare the line variable STRING and test NOT EOF before each read.
  3. Read each line exactly once.
  4. Write only a line not equal to the empty string.
  5. Close both files; output lines A and BC after three reads.
  6. Empty input causes zero reads/writes; APPEND would preserve obsolete output lines.

Examiner tip

Indicative distinct points, not an official Cambridge mark allocation. State bounds, assumptions and intermediate states; practical teacher review remains required.

Question 2A random file has seven fixed-length records addressed 0..6. Each record stores Used:BOOLEAN, Key:INTEGER, Value:STRING. All are initially unused. Use h(Key)=Key MOD 7 and linear probing with wraparound. Explain insertion of (10,'A'), (17,'B'), (24,'C'). Write pseudocode to find key24, returning its record address or -1; stop on an unused record or after seven probes. No deletions occur. Show SEEK/GETRECORD use and the search trace.6 indicative marks

A random file has seven fixed-length records addressed 0..6. Each record stores Used:BOOLEAN, Key:INTEGER, Value:STRING. All are initially unused. Use h(Key)=Key MOD 7 and linear probing with wraparound. Explain insertion of (10,'A'), (17,'B'), (24,'C'). Write pseudocode to find key24, returning its record address or -1; stop on an unused record or after seven probes. No deletions occur. Show SEEK/GETRECORD use and the search trace.

Show indicative guidance

Worked guidance

  1. TYPE Entry
       DECLARE Used : BOOLEAN
       DECLARE Key : INTEGER
       DECLARE Value : STRING
    ENDTYPE
    DECLARE Record : Entry
    DECLARE Address : INTEGER
    DECLARE Probes : INTEGER
    DECLARE Result : INTEGER
    DECLARE Finished : BOOLEAN
    Address <- 24 MOD 7
    Probes <- 0
    Result <- -1
    Finished <- FALSE
    OPENFILE "Index.dat" FOR RANDOM
    WHILE (Probes < 7) AND (NOT Finished)
       SEEK "Index.dat", Address
       GETRECORD "Index.dat", Record
       Probes <- Probes + 1
       IF NOT Record.Used THEN
          Finished <- TRUE
       ELSE
          IF Record.Key = 24 THEN
             Result <- Address
             Finished <- TRUE
          ELSE
             Address <- (Address + 1) MOD 7
          ENDIF
       ENDIF
    ENDWHILE
    CLOSEFILE "Index.dat"
    OUTPUT Result
  2. All three remainders are 3. Insert10 at3; insert17 probes3 then4; insert24 probes3,4 then5. Finding24 visits3(key10),4(key17),5(key24), and returns5. Finding31 would visit3,4,5 then unused6 and return -1.
  3. The file's address convention is explicitly records from zero, as recommended by the guide. A byte-oriented implementation would need a documented record-length conversion. Insertion writes with SEEK followed by PUTRECORD; duplicate-key and full-file policies would also need specification in a complete application.

Self-marking points

View marking points
  1. Hash all three keys to address3; preserve colliding records rather than overwrite.
  2. Insert the records at 3,4,5 respectively.
  3. Open FOR RANDOM and SEEK a logical record address before GETRECORD.
  4. Read into the correctly structured record variable and stop at an unused record when there are no deletions.
  5. Advance with (Address+1) MOD 7 and bound probes to seven.
  6. Key24 returns address5 after three key comparisons; close the file.

Examiner tip

Indicative distinct points, not an official Cambridge mark allocation. State bounds, assumptions and intermediate states; practical teacher review remains required.

Question 3Design Cambridge pseudocode classes Counter and CappedCounter. Counter has private INTEGER Total, constructor NEW(Start), public Add(Amount), and public Value() RETURNS INTEGER. CappedCounter INHERITS Counter, has private Limit, calls SUPER.NEW(Start), and overrides Add: accept only nonnegative Amount when Value()+Amount<=Limit. Otherwise leave the state unchanged. Assume 0<=Start<=Limit. Construct (Start10, Limit12), call Add(1), Add(3), Add(1), and trace Value() after each. Explain encapsulation and polymorphic method choice.6 indicative marks

Design Cambridge pseudocode classes Counter and CappedCounter. Counter has private INTEGER Total, constructor NEW(Start), public Add(Amount), and public Value() RETURNS INTEGER. CappedCounter INHERITS Counter, has private Limit, calls SUPER.NEW(Start), and overrides Add: accept only nonnegative Amount when Value()+Amount<=Limit. Otherwise leave the state unchanged. Assume 0<=Start<=Limit. Construct (Start10, Limit12), call Add(1), Add(3), Add(1), and trace Value() after each. Explain encapsulation and polymorphic method choice.

Show indicative guidance

Worked guidance

  1. CLASS Counter
       PRIVATE Total : INTEGER
       PUBLIC PROCEDURE NEW(Start : INTEGER)
          Total <- Start
       ENDPROCEDURE
       PUBLIC PROCEDURE Add(Amount : INTEGER)
          Total <- Total + Amount
       ENDPROCEDURE
       PUBLIC FUNCTION Value() RETURNS INTEGER
          RETURN Total
       ENDFUNCTION
    ENDCLASS
    CLASS CappedCounter INHERITS Counter
       PRIVATE Limit : INTEGER
       PUBLIC PROCEDURE NEW(Start : INTEGER, Maximum : INTEGER)
          SUPER.NEW(Start)
          Limit <- Maximum
       ENDPROCEDURE
       PUBLIC PROCEDURE Add(Amount : INTEGER)
          IF (Amount >= 0) AND (SUPER.Value() + Amount <= Limit) THEN
             SUPER.Add(Amount)
          ENDIF
       ENDPROCEDURE
    ENDCLASS
    DECLARE C : CappedCounter
    C <- NEW CappedCounter(10,12)
    C.Add(1)
    OUTPUT C.Value()
    C.Add(3)
    OUTPUT C.Value()
    C.Add(1)
    OUTPUT C.Value()
  2. The first accepted call changes 10 to11. The proposed next value14 exceeds12 and is rejected, retaining11. The final accepted call reaches12 exactly. The inherited public Value method accesses the parent's private state; the child does not name that field.
  3. The same Add method name invokes the subclass override for a CappedCounter instance. This demonstrates selected inheritance/encapsulation/polymorphism concepts, not every OOP feature such as aggregation. Methods use the guide's dot-call convention rather than CALL C.Add.

Self-marking points

View marking points
  1. Parent constructor initialises a private INTEGER Total.
  2. Parent exposes Add and a returning Value method.
  3. Subclass declares private Limit and initialises parent using SUPER.NEW.
  4. Override checks nonnegative Amount and the inclusive cap.
  5. Accepted calls delegate to SUPER.Add without direct access to private Total.
  6. Values are 11,11,12; subclass Add is chosen on the subclass instance, and external code uses methods rather than direct state writes.

Examiner tip

Indicative distinct points, not an official Cambridge mark allocation. State bounds, assumptions and intermediate states; practical teacher review remains required.

Question 4Write Python3 read_mean(path) that opens a UTF-8 text file for reading, converts each line to an integer, skips ValueError lines and negative integers, and returns the mean of accepted integers or None if none. Return None for FileNotFoundError, but do not hide every possible exception. For lines '4', 'bad', '-2', '8', give the result and propose empty-file, missing-file and normal boundary tests. Explain how the file is closed.6 indicative marks

Write Python3 read_mean(path) that opens a UTF-8 text file for reading, converts each line to an integer, skips ValueError lines and negative integers, and returns the mean of accepted integers or None if none. Return None for FileNotFoundError, but do not hide every possible exception. For lines '4', 'bad', '-2', '8', give the result and propose empty-file, missing-file and normal boundary tests. Explain how the file is closed.

Show indicative guidance

Worked guidance

  1. def read_mean(path):
        total = 0
        count = 0
        try:
            with open(path, "r", encoding="utf-8") as source:
                for line in source:
                    try:
                        value = int(line.strip())
                    except ValueError:
                        continue
                    if value >= 0:
                        total += value
                        count += 1
        except FileNotFoundError:
            return None
        return total / count if count else None
  2. After4 the state is(total4,count1); bad is skipped, -2 is rejected, and8 gives(total12,count2). Return12/2=6.0. For an empty or all-invalid file, count remains0 and the conditional prevents division by zero.
  3. Tests include lines['0']=>0.0, ['-1']=>None, []=>None, and a nonexistent path=>None. The with statement closes the opened file. A permission error is deliberately not misreported as a missing file or silently swallowed. This is Python syntax, not an invented Cambridge TRY pseudocode dialect.

Self-marking points

View marking points
  1. Open in text read mode using a context manager.
  2. Convert each line and catch ValueError locally so later lines are still processed.
  3. Skip negative integers but accept zero.
  4. Accumulate total/count and divide only when count>0.
  5. Catch FileNotFoundError specifically and return None.
  6. Result is6.0; empty/missing gives None, line0 gives0.0; with closes the file even on an exception.

Examiner tip

Indicative distinct points, not an official Cambridge mark allocation. State bounds, assumptions and intermediate states; practical teacher review remains required.

Question 5Audit.txt initially has lines START and OLD. Using Cambridge pseudocode, append one line OK without reading or replacing the old file. State contents after one run and after a second run. Explain whether the operation is idempotent and how WRITE mode would change the result.4 indicative marks

Audit.txt initially has lines START and OLD. Using Cambridge pseudocode, append one line OK without reading or replacing the old file. State contents after one run and after a second run. Explain whether the operation is idempotent and how WRITE mode would change the result.

Cambridge 2027: Direct conceptual match

Checked two-run state transition and guide section9.1 APPEND/WRITE semantics; no real file access is performed.

AI-assisted placement. Independent teacher approval pending.

Show indicative guidance

Worked guidance

  1. OPENFILE "Audit.txt" FOR APPEND
    WRITEFILE "Audit.txt", "OK"
    CLOSEFILE "Audit.txt"
  2. APPEND retains the two supplied lines and puts OK at the end. A second execution retains that third line too, then writes another OK.
  3. Thus contents after two runs are START, OLD, OK, OK. Repeating changes the state again, so this is not idempotent; WRITE would instead truncate the file and leave only OK after a run.

Self-marking points

View marking points
  1. Opens in APPEND, writes OK and closes.
  2. One run leaves START,OLD,OK in order.
  3. Second run adds another OK, so it is not idempotent.
  4. WRITE replaces previous contents rather than preserving them.

Examiner tip

Distinguish a repeated append from replacing a file with the same output.

All AS & A Level subjects