Cambridge AS & A Level9608

Programming

Computer Science 9608 Chapter Notes

What this chapter covers

Programming
ShareWhatsAppPost
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 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 'way of thinking' about programming. It's not a specific language, but rather an approach to structuring code to solve problems. Different paradigms are suited to different types of tasks. The main paradigms you need to know are:

  • Imperative: This is the most common paradigm. It uses statements that change a program's state. You write a sequence of commands for the computer to perform. High-level imperative languages include Python, Java, and C++.
  • Declarative: Instead of describing *how* to do something, you describe *what* you want to achieve. The language itself figures out how to get the result. SQL (for databases) and Prolog (for logic programming) are key examples.
  • Object-Oriented (OOP): An extension of imperative programming. It organises code into 'objects' which bundle data (attributes) and the methods (procedures) that operate on that data. This promotes code reuse and helps manage complexity in large systems.
  • Low-Level: This programming style is very close to the computer's own machine code. It deals directly with memory addresses and processor registers. Assembly language is the primary example. It gives the programmer fine-grained control but is difficult and time-consuming to write.

Key term

Programming Paradigm: A style or 'way' of programming, which defines the approach to structuring and writing code to solve problems.

Examiner insight

Examiners expect students to be able to compare and contrast paradigms, highlighting their key differences, not just define them in isolation.

Fun fact

The first major object-oriented language, Simula, was created in the 1960s to simulate complex real-world systems like ship movements in a fjord.

Worked example 13 marks

A programmer writes the following SQL statement: `SELECT StudentName FROM Students WHERE Course = 'Computer Science'`. Which programming paradigm is being used and why?

  1. 1
    1. Identify the paradigm: The paradigm being used is Declarative programming.
  2. 2
    1. Justify the choice: The programmer has stated *what* data they want (the names of students in Computer Science), not the step-by-step process of how to find it.
  3. 3
    1. Contrast with other paradigms: An imperative approach would involve opening the student file, looping through each record, checking if the course is 'Computer Science', and if so, adding the name to a list, before finally printing the list. The SQL statement abstracts all of this away.

Recap

  • A programming paradigm is a style of programming.
  • Imperative programming uses a sequence of commands to change program state.
  • Declarative programming focuses on the desired result, not the process.
  • Object-Oriented Programming (OOP) bundles data and methods into objects.
  • Low-level programming works directly with the computer's hardware architecture.

Quick check

  1. Which paradigm focuses on describing 'what' the result should be, rather than 'how' to achieve it?1 mark
  2. Give one example of a low-level language.1 mark

2. Procedures and Functions

Structured programming is an approach that aims to improve the clarity and quality of code by breaking a large program down into smaller, self-contained modules. The two main types of modules are procedures and functions.

  • Procedure: A subroutine that performs a specific task but does not return a value. You 'call' a procedure to execute its code. For example, a procedure might print a menu to the screen.
  • Function: A subroutine that performs a task and *must* return a single value. Because it returns a value, a function call is always used within an expression, for example, being assigned to a variable or used in a print statement.

Both use a 'header' which defines their name and any parameters they accept. This header is also known as the 'procedure/function interface'. Using procedures and functions promotes modularity and code reuse, making programs easier to write, test, and debug.

Key term

Modularity: The concept of breaking down a large program into smaller, self-contained, and manageable subroutines or modules.

Common pitfall

Forgetting that a function must be used in an expression (e.g., `Result <- MyFunction()`), whereas a procedure is called as a standalone statement (e.g., `CALL MyProcedure()`).

Worked example 13 marks

Write a pseudocode procedure called `ShowWelcome` that takes a user's name as a parameter and displays a personalised welcome message.

  1. 1

    PROCEDURE ShowWelcome(Username : STRING)

  2. 2

    OUTPUT "Welcome to the system, " + Username

  3. 3

    ENDPROCEDURE

  4. 4

    // Example of how to call the procedure:

  5. 5

    CALL ShowWelcome("Alice")

Worked example 24 marks

Write a pseudocode function called `CalculateArea` that takes the length and width of a rectangle as parameters and returns its area. Show how to call this function to find the area of a 10x5 rectangle and store the result in a variable.

  1. 1

    FUNCTION CalculateArea(Length : REAL, Width : REAL) RETURNS REAL

  2. 2

    RETURN Length * Width

  3. 3

    ENDFUNCTION

  4. 4

    // Example of how to call the function:

  5. 5

    DECLARE MyArea : REAL

  6. 6

    MyArea <- CalculateArea(10, 5)

  7. 7

    OUTPUT MyArea

Recap

  • Structured programming breaks problems into smaller modules.
  • A procedure is a subroutine that performs a task and does not return a value.
  • A function is a subroutine that performs a task and must return a value.
  • A function call is always part of an expression.
  • A procedure call is a standalone statement.
  • Using procedures and functions makes code modular, reusable, and easier to debug.

Quick check

  1. What is the key difference between a procedure and a function?2 marks

3. Parameter Passing: By Value vs. By Reference

When we call a procedure or function, we often need to pass data to it. The values we send are called 'arguments', and the variables in the subroutine that receive these values are called 'parameters'. There are two main ways to pass this data:

  • Pass by Value: The subroutine receives a *copy* of the argument's data. Any changes made to the parameter inside the subroutine do not affect the original variable in the calling code. This is the default method in many languages and is safer as it prevents accidental modification of data.
  • Pass by Reference: The subroutine receives the *memory address* of the argument. This means the parameter becomes an alias for the original variable. Any changes made to the parameter inside the subroutine *will* change the value of the original variable. This is necessary when you want a procedure to modify its input arguments.

Key term

Pass by Reference: A method of passing a parameter to a subroutine where the memory address of the original data is passed, allowing the subroutine to modify the original variable.

Examiner insight

Marks are often awarded for correctly tracing the state of variables through a subroutine call, demonstrating a clear understanding of the difference between pass by value and pass by reference.

Worked example 14 marks

Consider the following pseudocode. What is the final output?

PROCEDURE ChangeValues(BYVALUE A : INTEGER, BYREF B : INTEGER) A <- A * 2 B <- B * 2 ENDPROCEDURE

DECLARE X : INTEGER <- 10 DECLARE Y : INTEGER <- 20

CALL ChangeValues(X, Y)

OUTPUT X, Y

  1. 1
    1. Initial State: `X` is 10, `Y` is 20.
  2. 2
    1. Procedure Call: `ChangeValues` is called. `X` is passed by value to parameter `A`. `Y` is passed by reference to parameter `B`.
  3. 3
    1. Inside the Procedure:
    • A copy of `X` (value 10) is made for `A`. `A` becomes `10 * 2 = 20`. This does not affect `X`.
    • The address of `Y` is used for `B`. `B` becomes `20 * 2 = 40`. Since `B` refers to `Y`, the original `Y` is changed to 40.
  4. 4
    1. After the Procedure: The procedure ends. `X` remains unchanged. `Y` has been modified.
  5. 5
    1. Final Output: The program will output `10, 40`.

Recap

  • An argument is the data sent to a subroutine; a parameter is the variable that receives it.
  • Pass by value sends a copy of the data, so the original variable is unchanged.
  • Pass by reference sends the memory address of the data, allowing the original variable to be modified.
  • Use pass by value for safety and to prevent unintended side effects.
  • Use pass by reference when a procedure needs to alter the value of one or more of its arguments.

Quick check

  1. If a subroutine needs to return multiple updated values, which parameter passing method is most suitable for its parameters?1 mark

4. Using Record Data Structures

Simple variables can hold one piece of data, like a number or a string. Arrays can hold many pieces of data, but they must all be of the same type. Often, we need to group related items of *different* types. For this, we use a record. A record is a composite data structure that groups a collection of related fields under a single name. For example, to store information about a student, you might want to group their ID (an integer), name (a string), and date of birth (a date). A record allows you to do this. You first define the 'template' or 'type' for the record, then you can declare variables of that record type.

Key term

Record: A composite data structure that groups together a collection of related data items (fields), which can be of different data types.

Common pitfall

Confusing a record with an array. An array holds multiple items of the *same* data type, while a record holds a fixed collection of items of potentially *different* data types.

Worked example 13 marks

Define a record type in pseudocode for a `Book` with fields for `Title` (string), `Author` (string), and `PublicationYear` (integer).

  1. 1

    TYPE Book

  2. 2

    DECLARE Title : STRING

  3. 3

    DECLARE Author : STRING

  4. 4

    DECLARE PublicationYear : INTEGER

  5. 5

    ENDTYPE

Worked example 24 marks

Using the `Book` type from the previous example, write pseudocode to declare a variable called `MyBook`, assign it the details of a book, and then output the details.

  1. 1

    // Assumes the Book TYPE definition from the previous example exists

  2. 2

    DECLARE MyBook : Book

  3. 3

    MyBook.Title <- "Computer Science"

  4. 4

    MyBook.Author <- "Langfield and Duddell"

  5. 5

    MyBook.PublicationYear <- 2019

  6. 6

    OUTPUT "Title: ", MyBook.Title

  7. 7

    OUTPUT "Author: ", MyBook.Author

  8. 8

    OUTPUT "Year: ", MyBook.PublicationYear

Recap

  • A record is used to group related data of different types.
  • You must first define the record's structure using a TYPE declaration.
  • Individual data items within a record are called fields.
  • You can declare variables of your new record type.
  • Use dot notation (e.g., `VariableName.FieldName`) to access individual fields.

Quick check

  1. What is the main difference between an array and a record?2 marks

5. File Handling Fundamentals

Variables and data structures like arrays and records exist in RAM, which is volatile. When the program ends or the power is turned off, all that data is lost. To store data permanently, we must write it to a file on a secondary storage device like a hard drive. This is called persistent storage.

There are three main types of file access:

  • Serial: Records are stored one after another, in the order they were added. To find a specific record, you must start at the beginning and read every record until you find it.
  • Sequential: A special type of serial file where the records are sorted into order based on a key field. This can make searching more efficient.
  • Random: Records can be accessed directly using their position or a key field, without reading through the preceding records. This is much faster for non-sequential access.

Basic file operations include:

  • `OPENFILE <filename> FOR <MODE>`: Prepares a file for use. Mode can be `READ`, `WRITE` (overwrite), or `APPEND` (add to end).
  • `READFILE <filename>, <variable>`: Reads a line or record from an open file into a variable.
  • `WRITEFILE <filename>, <data>`: Writes data to an open file.
  • `CLOSEFILE <filename>`: Closes the file, saving changes and freeing up resources.

Key term

Persistent Storage: The storage of data in a non-volatile device (like a hard disk) that remains intact even after the program has terminated or the computer is shut down.

Examiner insight

Candidates must use the correct pseudocode keywords (e.g., OPENFILE, READFILE, WRITEFILE, CLOSEFILE) and specify the file mode (READ, WRITE, APPEND) to gain full marks.

Worked example 15 marks

Write a pseudocode algorithm to create a file called `SCORES.TXT`, ask the user to enter three names and scores, and write each name and score to a new line in the file.

  1. 1

    OPENFILE "SCORES.TXT" FOR WRITE

  2. 2

    FOR i <- 1 TO 3

  3. 3

    OUTPUT "Enter name: "

  4. 4

    INPUT Name

  5. 5

    OUTPUT "Enter score: "

  6. 6

    INPUT Score

  7. 7

    WRITEFILE "SCORES.TXT", Name + "," + Score

  8. 8

    NEXT i

  9. 9

    CLOSEFILE "SCORES.TXT"

Worked example 24 marks

Write a pseudocode algorithm to read every line from `SCORES.TXT` and display it on the screen.

  1. 1

    OPENFILE "SCORES.TXT" FOR READ

  2. 2

    WHILE NOT EOF("SCORES.TXT")

  3. 3

    READFILE "SCORES.TXT", FileLine

  4. 4

    OUTPUT FileLine

  5. 5

    ENDWHILE

  6. 6

    CLOSEFILE "SCORES.TXT"

Recap

  • File handling is used for persistent data storage.
  • Basic file operations are OPEN, READ, WRITE, and CLOSE.
  • File modes include READ (for input), WRITE (for output, overwrites existing), and APPEND (for output, adds to end).
  • Serial files store records in the order they were added.
  • Sequential files are serial files sorted by a key field.
  • The `EOF()` function is used to detect the end of a file when reading.

Quick check

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

6. Robust Programming with Exception Handling

An exception is an error that occurs during the execution of a program (a run-time error). Examples include trying to divide by zero, accessing a file that doesn't exist, or a user entering text when a number is expected. Without any special handling, an exception will cause the program to crash, which is not user-friendly.

Exception handling is a mechanism that allows a programmer to write code to deal with these errors gracefully. Instead of crashing, the program can detect the error, display a helpful message, and either continue or terminate in a controlled way. The standard structure for this is a `TRY...CATCH` block (sometimes called `TRY...EXCEPT`).

  • TRY: You place the code that might cause an exception inside the `TRY` block.
  • CATCH: If an exception occurs in the `TRY` block, the program immediately jumps to the `CATCH` block. The code in the `CATCH` block is the 'plan B' - it handles the error, for example by printing a message like "Invalid input, please enter a number."

Key term

Exception Handling: A programming construct that allows a program to detect and respond to run-time errors (exceptions), preventing the program from crashing.

Common pitfall

Using normal conditional `IF...THEN...ELSE` statements to check for errors that are better suited for exception handling, such as file I/O errors or invalid type casting.

Fun fact

The 1996 Ariane 5 rocket explosion, one of the most expensive software failures in history ($370 million), was caused by an unhandled exception when converting a 64-bit floating-point number to a 16-bit integer.

Worked example 15 marks

A program asks a user for their age. Write pseudocode that uses exception handling to prevent the program from crashing if the user enters text instead of a number.

  1. 1

    DECLARE UserAge : INTEGER

  2. 2

    DECLARE ValidInput : BOOLEAN <- FALSE

  3. 3

    WHILE ValidInput = FALSE

  4. 4

    TRY

  5. 5

    OUTPUT "Please enter your age: "

  6. 6

    INPUT UserAge

  7. 7

    ValidInput <- TRUE

  8. 8

    OUTPUT "Thank you. You entered ", UserAge

  9. 9

    CATCH

  10. 10

    OUTPUT "Error: Invalid input. Please enter a whole number."

  11. 11

    ENDTRY

  12. 12

    ENDWHILE

Recap

  • An exception is a run-time error that disrupts program flow.
  • Exception handling allows a program to manage errors without crashing.
  • The `TRY` block contains code that might cause an error.
  • The `CATCH` block contains the code that runs if an error is detected.
  • Using exception handling makes programs more robust and user-friendly.
  • Common exceptions include invalid user input, file not found, and division by zero.

Quick check

  1. In a TRY...CATCH structure, which block contains the code that you expect might fail?1 mark

End-of-chapter exercise

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

  1. Define 'imperative programming paradigm' and 'declarative programming paradigm', giving an example use case for each.4 marks
  2. Explain the difference between a parameter and an argument in the context of subroutines.2 marks
  3. Write pseudocode for a function `CalculateVolume` that takes the length, width, and height of a cuboid as parameters and returns its volume. Show how this function would be called.4 marks
  4. A program uses a procedure `Swap(Num1, Num2)` to swap the values of two integer variables. Explain, with the aid of a pseudocode example, why passing the parameters by value would not work and why they must be passed by reference.5 marks
  5. Define a record type in pseudocode called `Employee`. It should contain the fields `EmployeeID` (Integer), `LastName` (String), `HourlyRate` (Real), and `HoursWorked` (Integer). Then, declare an array of 100 employees of this type.4 marks
  6. A sequential file, `MEMBERS.DAT`, stores member details. Each record has `MemberID`, `Name`, and `JoinDate` fields. Write a pseudocode algorithm to read the file and display the details of all members who joined after '01/01/2023'.6 marks
  7. Compare and contrast the use of a function and a procedure. Your answer should refer to how they are called, how they return data, and their typical use cases.6 marks
  8. A program asks the user to enter their age. It then calculates and prints the year they were born. This can cause run-time errors. Identify two potential exceptions that could occur and write a pseudocode algorithm using exception handling to manage them gracefully.7 marks
  9. Describe the key characteristics of the object-oriented paradigm. Explain how its approach to structuring a program differs from the imperative paradigm.6 marks
  10. Explain what is meant by an exception. Describe, using a suitable example, why exception handling is an important feature of a robust program.5 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