Cambridge AS & A Level9608

Further programming

Computer Science 9608 Chapter Notes

What this chapter covers

Further programming
ShareWhatsAppPost
Further programming notes

Unable to load PDF

The notes viewer could not load. Please refresh the page.

Read online free. Download a watermarked copy with a free account.

Read the notes

The full Further programming notes as text: skim, search, and jump between subtopics.

~13 min read

1. Understanding Programming Paradigms

A programming paradigm is a fundamental style or approach to programming. It's not a specific language, but a way of thinking about and structuring code. Different paradigms are suited to different types of problems. The A-Level course focuses on four main types: low-level, imperative, object-oriented, and declarative. A single language, like Python, can often support multiple paradigms.

Key term

Programming Paradigm: A style or 'way' of programming that provides a set of concepts and principles for designing and implementing programs.

Examiner insight

Examiners expect students to be able to compare and contrast different paradigms, not just define them in isolation. Use examples to support your points.

Common pitfall

Confusing a programming paradigm (e.g., object-oriented) with a specific programming language (e.g., Python). Many languages support multiple paradigms.

Worked example 14 marks

A programmer is writing code that consists of a sequence of commands that change the program's state. For example, `X = X + 1`. Another programmer is writing code that describes the desired result without specifying the step-by-step procedure, for example, `SELECT Name FROM Students WHERE Age > 18`. Identify the paradigm used by each programmer and justify your answer.

  1. 1

    Programmer 1 is using the Imperative paradigm.

  2. 2

    Justification: Imperative programming focuses on describing 'how' to achieve a result through a sequence of explicit commands that modify the program's state (e.g., changing the value of variable X).

  3. 3

    Programmer 2 is using the Declarative paradigm.

  4. 4

    Justification: Declarative programming focuses on describing 'what' the result should be, leaving the 'how' to the language implementation. The SQL query states the desired outcome (a list of names) without detailing the steps to find and filter them.

Recap

  • A programming paradigm is a style of programming.
  • Low-level programming deals with machine-specific instructions.
  • Imperative programming uses a sequence of commands to change program state.
  • Object-oriented programming bundles data and methods into objects.
  • Declarative programming describes the desired result, not the steps to get there.

Quick check

  1. Name the four programming paradigms you need to know.2 marks
  2. Which paradigm is SQL (Structured Query Language) an example of?1 mark

2. Defining and Using Record Structures

A record is a user-defined, composite data type that groups together related data items, called fields, under a single name. Unlike an array, the fields in a record can be of different data types. For example, you could create a 'Student' record with fields for their name (String), ID (Integer), and average grade (Real). First, you define the structure of the record (the 'type'), and then you can declare variables of that new type.

TYPE <RecordName> DECLARE <FieldName1> : <DataType1> DECLARE <FieldName2> : <DataType2> ... ENDTYPE

DECLARE <VariableName> : <RecordName>

Key term

Record: A composite data type that groups a collection of fields, potentially of different data types, into a single entity.

Examiner insight

Marks are often awarded for correctly defining a record type and then declaring a variable of that new type. Both steps are required for full marks.

Common pitfall

Forgetting to define the record TYPE before trying to declare a variable of that type. You must create the template before you can create an instance.

Worked example 14 marks

A car dealership needs to store information about its cars. For each car, they need to store its Make (e.g., 'Ford'), Model (e.g., 'Focus'), Year (e.g., 2021), and Price (e.g., 15000.50).(a) Write pseudocode to define a record type called `CarType` for this purpose.(b) Declare a variable called `NewCar` of the type `CarType`.(c) Show how you would assign the value 2022 to the `Year` field of the `NewCar` variable.

  1. 1

    (a) Defining the record type:

  2. 2

    TYPE CarType

  3. 3

    DECLARE Make : STRING

  4. 4

    DECLARE Model : STRING

  5. 5

    DECLARE Year : INTEGER

  6. 6

    DECLARE Price : REAL

  7. 7

    ENDTYPE

  8. 8

    (b) Declaring a variable of the record type:

  9. 9

    DECLARE NewCar : CarType

  10. 10

    (c) Assigning a value to a field:

  11. 11

    NewCar.Year <- 2022

Recap

  • A record groups related data of different types.
  • First, you must define the record TYPE.
  • Then, you can DECLARE variables of that new type.
  • Access individual fields using dot notation (e.g., VariableName.FieldName).
  • Records are essential for organising complex data and for file processing.

Quick check

  1. Write pseudocode to define a record type `Book` with fields `Title` (String) and `ISBN` (String).2 marks

3. Working with Sequential Files

File handling allows programs to store data permanently on secondary storage. A sequential file is the simplest type, where data is read or written in order, one record after another, from beginning to end. To use a file, you must first open it in a specific mode (e.g., READ, WRITE, or APPEND). After processing, it is crucial to close the file to save changes and free up system resources. You cannot insert or delete data in the middle of a sequential file; to update a record, you typically read the entire original file, make changes, and write the data to a new file.

OPENFILE <filename> FOR READ/WRITE/APPEND

READFILE <filename>, <variable>

WRITEFILE <filename>, <data>

CLOSEFILE <filename>

Key term

Sequential File: A file where records are stored and accessed one after another in the order they were written.

Examiner insight

Candidates must show the correct sequence of file operations: open, process (often in a loop), and then close. Forgetting to close the file is a common and penalised omission.

Common pitfall

Forgetting to close the file after processing. This can lead to data loss or corruption as the operating system may not write the final buffer to disk.

Worked example 16 marks

A text file, `Scores.txt`, contains a list of student scores, one per line. Write a pseudocode algorithm to read all the scores from the file, find the highest score, and display it on the screen.

  1. 1

    DECLARE HighestScore : INTEGER

  2. 2

    DECLARE CurrentScore : INTEGER

  3. 3

    HighestScore <- -1 // Initialise with a value lower than any possible score

  4. 4

    OPENFILE "Scores.txt" FOR READ

  5. 5

    WHILE NOT EOF("Scores.txt")

  6. 6

    READFILE "Scores.txt", CurrentScore

  7. 7

    IF CurrentScore > HighestScore THEN

  8. 8

    HighestScore <- CurrentScore

  9. 9

    ENDIF

  10. 10

    ENDWHILE

  11. 11

    CLOSEFILE "Scores.txt"

  12. 12

    OUTPUT "The highest score is: ", HighestScore

Recap

  • Sequential files store data in a specific order.
  • You must open a file before you can read from or write to it.
  • The main modes are READ (for input), WRITE (for new output), and APPEND (to add to the end).
  • Always close a file after you have finished using it.
  • To read the whole file, use a loop that continues until the End-Of-File (EOF) is reached.

Quick check

  1. What is the difference between opening a file in WRITE mode versus APPEND mode?2 marks

4. Advanced File Handling: Random Files

A random access file allows you to access any record directly, without having to read through the preceding records. This is much faster than sequential access if you need to retrieve or update specific records. This is achieved by ensuring all records in the file have the same fixed length. The program can then calculate the exact byte position of any record by using the formula: Position = (RecordNumber - 1) * RecordLength. You can then 'seek' to that position to read or write the record.

Position = (RecordNumber - 1) * RecordLength

GET <filename>, <RecordNumber>, <RecordVariable>

PUT <filename>, <RecordNumber>, <RecordVariable>

Key term

Random Access File: A file that allows records to be accessed directly in any order, typically by using a record number or key.

Examiner insight

Questions on random files often involve calculating a record's position or understanding the process. Clearly stating the need for fixed-length records and the direct access method will gain marks.

Common pitfall

Assuming records in a random file can be of variable length. Random access relies on fixed-length records to calculate positions.

Fun fact

Databases and file systems use an advanced form of random access called hashing or B-Trees to find records almost instantly, even in files containing billions of records.

Worked example 15 marks

A random access file, `Products.dat`, stores product records of type `ProductRec`. Each record is 50 bytes long. Write pseudocode to update the price of the product at record number 25 to 99.99. The record has a field named `Price`.

  1. 1

    // First, define the record structure (assumed from question)

  2. 2

    TYPE ProductRec

  3. 3

    // ... other fields

  4. 4

    DECLARE Price : REAL

  5. 5

    // ... other fields

  6. 6

    ENDTYPE

  7. 7

    // Main algorithm

  8. 8

    DECLARE ItemToUpdate : ProductRec

  9. 9

    DECLARE RecordNum : INTEGER

  10. 10

    RecordNum <- 25

  11. 11

    OPENFILE "Products.dat" FOR RANDOM

  12. 12

    // In a real exam, you might use GET/PUT or SEEK/READ/WRITE

  13. 13

    // Using GET/PUT which is common in pseudocode

  14. 14

    GET "Products.dat", RecordNum, ItemToUpdate

  15. 15

    ItemToUpdate.Price <- 99.99

  16. 16

    PUT "Products.dat", RecordNum, ItemToUpdate

  17. 17

    CLOSEFILE "Products.dat"

Recap

  • Random access files allow direct access to any record.
  • This requires all records to have a fixed length.
  • The position of a record is calculated using its number and the fixed record length.
  • Use GET or PUT (or SEEK/READ/WRITE) operations to access records directly.
  • Random files are much more efficient than sequential files for non-linear data access.

Quick check

  1. What is the essential property of records in a random access file?1 mark
  2. If a record is 120 bytes long, what is the starting byte position of record number 10? (Assume records are numbered from 1).2 marks

5. Robust Programming with Exception Handling

An exception is an error that occurs during the execution of a program, disrupting its normal flow. Examples include trying to divide by zero, accessing a file that doesn't exist, or converting a non-numeric string to an integer. Without exception handling, these errors would cause the program to crash. Exception handling provides a structured way to catch these errors and execute special code to deal with them gracefully. This is typically done using a `TRY...CATCH` or `TRY...EXCEPT` block. Code that might cause an error is placed in the `TRY` block. If an error occurs, the program jumps to the `CATCH` block, which contains the code to handle the error, such as displaying a user-friendly message.

TRY // Code that might cause an error CATCH <ExceptionType> // Code to run if the error occurs ENDTRY

Key term

Exception: An unexpected event or error that occurs during the execution of a program, disrupting its normal flow.

Examiner insight

Simply stating 'to prevent the program from crashing' is a good start, but better answers explain that exception handling allows the program to deal with the error gracefully, perhaps by logging it, retrying the operation, or informing the user with a clear message.

Common pitfall

Putting the entire program inside a single, massive TRY block. Exception handling should be targeted at specific lines of code that are known to be risky, like file I/O or user input conversion.

Worked example 14 marks

A program asks the user to enter their age. Write a pseudocode snippet that reads the age, converts it to an integer, and handles the error that would occur if the user enters non-numeric text (e.g., 'twelve'). If an error occurs, it should output 'Invalid input. Please enter a number.'

  1. 1

    DECLARE UserInput : STRING

  2. 2

    DECLARE Age : INTEGER

  3. 3

    OUTPUT "Please enter your age: "

  4. 4

    INPUT UserInput

  5. 5

    TRY

  6. 6

    Age <- STRING_TO_INT(UserInput)

  7. 7

    OUTPUT "Your age is: ", Age

  8. 8

    CATCH InvalidInputError

  9. 9

    OUTPUT "Invalid input. Please enter a number."

  10. 10

    ENDTRY

Recap

  • An exception is a runtime error.
  • Exception handling prevents programs from crashing.
  • The `TRY` block contains code that could potentially cause an error.
  • The `CATCH` or `EXCEPT` block contains the code that runs if an error is caught.
  • Good exception handling makes programs more robust and user-friendly.

Quick check

  1. Name two types of runtime errors that could be caught by exception handling.2 marks

6. Tools: IDEs, Debuggers, and Translators

Modern programming is supported by powerful tools, often bundled in an Integrated Development Environment (IDE).

Code Editors: These are more than just text editors. They provide features like syntax highlighting (colouring keywords), automatic indentation (prettyprinting), and code completion (suggesting variable and function names) to improve readability and speed up coding.

Translators: A program written in a high-level language must be translated into machine code. A Compiler translates the entire source code at once into an executable file. This file can be run independently and is very fast. An Interpreter translates and executes the code line by line. This is slower but makes it easier to test and debug code interactively.

Debuggers: A debugger is a tool for finding and fixing logic errors (bugs). Key features include Breakpoints (pausing execution at a specific line), Stepping (executing code one line at a time), and Watch Windows (inspecting the value of variables as the program runs).

Key term

Debugger: A software tool used to test and find errors (bugs) in other programs by allowing the programmer to control execution and inspect the program's state.

Examiner insight

When asked about debugging tools, be specific. Instead of saying 'you can check variables', say 'you can add variables to a watch window to monitor their values as the program executes'.

Common pitfall

Confusing syntax errors (e.g., a typo, caught by the compiler/interpreter before running) with logic errors (e.g., using '+' instead of '-', which causes incorrect output and must be found using a debugger).

Fun fact

The term 'bug' was popularized after a moth was found trapped in a relay of the Harvard Mark II computer in 1947, causing it to malfunction. The operators 'debugged' the computer by removing the insect.

Worked example 14 marks

A programmer is developing a complex application that needs to run as fast as possible once it is delivered to clients. During development, however, they need to frequently test small changes. Should they use a compiler or an interpreter during(i) development and(ii) for the final product? Justify your answers.

  1. 1

    (i) During development, an interpreter is often preferred.

  2. 2

    Justification: An interpreter allows for rapid testing as it executes code line by line without a lengthy compilation step. This makes it easier to debug and test small changes quickly.

  3. 3

    (ii) For the final product, a compiler must be used.

  4. 4

    Justification: A compiler translates the entire program into optimized machine code, creating a standalone executable. This runs much faster than an interpreted program, which is essential for performance-critical applications.

Worked example 24 marks

A loop in a program is not terminating correctly. Which two debugger features would be most useful for investigating this bug, and how would they be used?

  1. 1

    Feature 1: Breakpoint. The programmer would place a breakpoint on the first line inside the loop.

  2. 2

    Usage: This will cause the program to pause every time it is about to start a new iteration of the loop.

  3. 3

    Feature 2: Watch Window. The programmer would add the loop control variable and any variables in the loop's condition to the watch window.

  4. 4

    Usage: Each time the program pauses at the breakpoint, the programmer can inspect the values of these variables in the watch window to see how they are changing and identify why the termination condition is not being met.

Recap

  • IDEs provide tools like editors, compilers, and debuggers.
  • Compilers translate all code at once for fast execution; interpreters translate line-by-line for easy debugging.
  • Debuggers help find logic errors.
  • Breakpoints pause program execution at a specific line.
  • Watch windows let you monitor variable values during execution.
  • Stepping executes code one line at a time.

Quick check

  1. What is the purpose of a breakpoint in a debugger?1 mark
  2. State one advantage of a compiler over an interpreter.1 mark

End-of-chapter exercise

Test yourself on the whole chapter. Work through these before moving on.

  1. Compare the imperative programming paradigm with the declarative programming paradigm, giving an example of a language or context for each.4 marks
  2. Write pseudocode to define a record type named `Student` with the fields `StudentID` (Integer), `LastName` (String), and `IsFeePaid` (Boolean). Then, declare an array named `ClassList` to hold 30 records of this type.3 marks
  3. Explain the purpose of exception handling in robust program design. Provide a pseudocode example showing how you would handle a 'file not found' error when attempting to open a file for reading.5 marks
  4. Describe two features commonly found in the editor of an Integrated Development Environment (IDE) that help a programmer write code more efficiently.4 marks
  5. A company stores 100,000 customer records in a sequential file. Explain why this is an inefficient choice if the company's main activity is looking up individual customer records by their unique ID to answer phone queries. Suggest a more appropriate file structure and justify your choice.4 marks
  6. Distinguish between a compiler and an interpreter. For each, state one advantage of its use.4 marks
  7. A program has a logic error where a variable that should be counting down from 10 to 0 is instead counting up. Describe, step-by-step, how a programmer could use a debugger's 'breakpoint' and 'watch window' features to locate the cause of this error.5 marks
  8. Write a pseudocode algorithm that reads each line from a text file named `DataIn.txt`, counts the number of lines, and writes this total count as a single integer to a new file named `CountOut.txt`.6 marks
  9. Explain the steps involved in reading and then updating the 50th record in a random access file named `Stock.dat`. Assume each record is 100 bytes long and records are numbered from 1. You do not need to write code, but you should describe the calculations and operations involved.5 marks
  10. Low-level and object-oriented are two programming paradigms. Give one key characteristic of each paradigm and an example of a situation where each would be the preferred choice.4 marks

Go deeper

Practise and revise with member-only material for this chapter.

Free notes are just the start.

Unlock every Workbook and Chapter at a Glance, and generate your own worksheets and predicted papers.

Explore plans

Related chapters