Ch 3 · 11 Programming · AS & A Level Computer Science 9618

Topic 3 of 3 in Algorithms, Data Structures and Programming — AS & A Level Computer Science 9618 — 109 lessons.

Introduction

This lesson covers the pseudocode statements you need to write any AS program: declarations, expressions, built-in functions, selection, the three kinds of loop, and procedures and functions with parameters. Paper 2 marks your pseudocode, so follow the Cambridge conventions shown here. (Syllabus topic 11: sections 11.1–11.3.)

Key ideas — 11.1 (a) Constants, variables and assignment

A constant is used for a value that does not change while the program runs (a tax rate, the number of students): if it ever changes, it is edited in one place, and the name makes the code easier to read.

🧑‍🏫 Teacher's explanation

Imagine you are organizing a massive school gala. You have a fixed rule that every ticket costs exactly £15.00—this is a constant. No matter how many people attend, that price stays the same throughout the event. However, you also need to keep track of how many people have actually arrived. This number changes every time someone walks through the door, so you use a variable to store it.

📖 Definitions

🔍 Worked example — Easy

A program needs to store the value of π (3.142) and the current temperature of a room. Write the pseudocode declarations and the initial assignment for both.

🔍 Worked example — Standard

A shop sells apples. The tax rate is fixed at 15\%. The price of an apple is 0.50. Write pseudocode to declare the tax rate constant and the price variable, then assign the values.

🔍 Worked example — Exam-style

An algorithm calculates the total cost of n items. The unit price is 5.00 and the quantity is 10. Write pseudocode to declare the constant for unit price, the variable for quantity, and the variable for total cost, then perform the calculation using assignment.

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

Key ideas — 11.1 (b) Expressions, input and output

🧑‍🏫 Teacher's explanation

Think of programming as giving a recipe to a very literal-minded chef. Expressions are the mathematical instructions in that recipe, like 'double the flour'. Input is the ingredients being handed to the chef, and Output is the final dish being served on a plate.

📖 Definitions

🔍 Worked example — Easy

A program asks for a user's age. If the age is 18 or older, it outputs 'Adult', otherwise it outputs 'Minor'. Write the pseudocode.

🔍 Worked example — Standard

Calculate the remainder and the integer quotient of 25 divided by 4 using pseudocode.

🔍 Worked example — Exam-style

A user inputs a string 'Code' and an integer 9618. The program should output 'Course: Code 9618'. Write the pseudocode.

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

Key ideas — 11.1 (c) Built-in functions and library routines

A built-in function or library routine is pre-written and tested, so it saves time. In the exam, string manipulation functions will always be given, and any function not in the pseudocode guide is provided in the question. Common ones:

🧑‍🏫 Teacher's explanation

Imagine you are building a complex Lego castle. Instead of manufacturing every single plastic brick yourself from raw molten plastic, you buy pre-made bricks like '2x4 red' or 'sloped grey' from a factory. These pre-made pieces are like built-in functions. They are already tested, they work perfectly, and they save you a massive amount of time. In programming, instead of writing a complex algorithm to figure out how to find the length of a word or how to convert a number to text, you simply call a 'library routine' that someone else has already written.

📖 Definitions

🔍 Worked example — Easy

Given the string $S \leftarrow \"Cambridge\"$, find the result of MID(S, 4, 3).

🔍 Worked example — Standard

Calculate the result of INT(RAND(6)) + 1.

🔍 Worked example — Exam-style

A user inputs a password $P \leftarrow \"A123B\"$. Write pseudocode to extract the first character and the last character, then convert the first character to its ASCII value.

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

Key ideas — 11.2 (a) Selection

CASE chooses between many values of one variable, more clearly than many nested IFs:

🧑‍🏫 Teacher's explanation

Selection is the process of making decisions within an algorithm. It allows a program to follow different paths of execution based on whether a specific condition is true or false. Think of it like a fork in the road: you approach a junction, check a signpost (the condition), and then choose which path to take.

📖 Definitions

🔍 Worked example — Easy

Write pseudocode to check if an integer variable Score is positive, zero, or negative.

🔍 Worked example — Standard

A variable UserChoice contains an integer. Write a CASE statement that outputs 'Start' for 1, 'Stop' for 2, and 'Reset' for 3. For any other value, output 'Error'.

🔍 Worked example — Exam-style

A program must assign a grade based on a variable Mark. If Mark is 80 or above, Grade is 'A'. If Mark is between 50 and 79 inclusive, Grade is 'B'. Otherwise, Grade is 'C'. Write the pseudocode.

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

If the temperature is above 100, the output should be "Boiling". If the temperature is between 0 and 100 (inclusive), the output should be "Liquid". If the temperature is below 0, the output should be "Frozen".

Key ideas — 11.2 (b) Loops

Justifying the choice: "A REPEAT loop is better for validating input, because the user must enter a value at least once before it can be checked." "A WHILE loop is better for reading a file, because the file may be empty, so the loop body must not run at all."

🧑‍🏫 Teacher's explanation

Imagine you are a coach training an athlete. If you tell them, "Do exactly 10 laps," you are using a count-controlled loop; you know the exact number of repetitions before they even start. If you say, "Run until you are tired," you are using a post-condition loop; they will definitely run at least one lap before they check if they are tired. Finally, if you say, "If you feel energetic, run a lap," you are using a pre-condition loop; if they are already tired, they might not run at all.

📖 Definitions

🔍 Worked example — Easy

Write pseudocode for a count-controlled loop that outputs the numbers from 5 down to 1.

🔍 Worked example — Standard

A program must ask a user for a password until they enter 'SECRET'. Write the pseudocode for this using a post-condition loop.

🔍 Worked example — Exam-style

Trace the following pseudocode and provide the final value of Total:\nTotal arrow 0\nNumber arrow 10\nWHILE Number > 0\n Total arrow Total + Number\n Number arrow Number - 3\nENDWHILE

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

Key ideas — 11.3 (a) Procedures

A procedure is a named, self-contained block of code that performs a task. It does not return a value, and is called with CALL.

🧑‍🏫 Teacher's explanation

Imagine you are following a recipe to bake a cake. A 'procedure' is like a sub-recipe, such as 'How to make frosting'. You don't get a single ingredient back at the end; instead, you perform a set of specific actions (mixing, whipping, pouring) that change the state of your kitchen. You 'call' the frosting procedure whenever you need it, rather than rewriting the whole mixing process every time you bake a different cake.

📖 Definitions

🔍 Worked example — Easy

Write a procedure named \texttt{GreetUser} that takes a string parameter \texttt{Name} and outputs 'Hello ' followed by the name.

🔍 Worked example — Standard

A procedure \texttt{DoubleValue} takes an integer parameter \texttt{Num} by value. If we call \texttt{CALL DoubleValue(5)}, what is the value of the original variable after the call?

🔍 Worked example — Exam-style

Trace the following pseudocode: \n\n\texttt{PROCEDURE UpdateScore(BYREF Score : INTEGER)\n Score <- Score + 10\nENDPROCEDURE\n\n\texttt{DECLARE PlayerScore : INTEGER}\nPlayerScore <- 50\nCALL UpdateScore(PlayerScore)\nOUTPUT PlayerScore

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

Key ideas — 11.3 (b) Parameters: by value and by reference

A procedure may have none, one or more parameters.

🧑‍🏫 Teacher's explanation

Imagine you have a very important notebook containing a secret code.

📖 Definitions

🔍 Worked example — Easy

Trace the following pseudocode:

🔍 Worked example — Standard

Trace the following pseudocode:

🔍 Worked example — Exam-style

A procedure is designed to swap two integer values. The programmer uses the following code:

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

PROCEDURE UpdateScore(BYREF S : INTEGER, BYVAL Points : INTEGER) S ← S + Points ENDPROCEDURE

Key ideas — 11.3 (c) Functions

A function performs a task and returns a single value. It is used in an expression: the return value replaces the call.

🧑‍🏫 Teacher's explanation

Imagine you are at a vending machine. You put in a coin (the input/parameter), the machine performs a complex internal process (the function body), and then it spits out a single soda (the return value). You don't just watch the machine work; you take that soda and use it—perhaps you drink it or give it to a friend. In programming, a function is a 'black box' that takes data, processes it, and hands back a single result that you can immediately use in a larger calculation.

📖 Definitions

🔍 Worked example — Easy

Write a function CalculateArea that takes Length and Width (both INTEGER) and returns the area as an INTEGER.

🔍 Worked example — Standard

A function IsEven takes an INTEGER and returns a BOOLEAN. Use it to check if Num is even and output 'Yes' if true, 'No' if false.

🔍 Worked example — Exam-style

Trace the following pseudocode:

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

Note: Use π = 3.142. [3 marks]

Key ideas — 11.3 (d) Terminology

🧑‍🏫 Teacher's explanation

Think of a subroutine (a procedure or a function) like a specialized kitchen appliance, such as a blender. The 'header' is the label on the front of the blender telling you what it is and what it needs (e.g., 'Fruit Blender: Input 2 Fruits, Output 1 Smoothie'). The 'interface' is the physical design—the size of the lid and the type of buttons—which tells you exactly how you must interact with it.

📖 Definitions

🔍 Worked example — Easy

Identify the components of the following function header: FUNCTION CalculateArea(Radius : REAL) RETURNS REAL

🔍 Worked example — Standard

Given the procedure PROCEDURE UpdateScore(PlayerID : INTEGER, Points : INTEGER) BY REFERENCE, identify the arguments if the call is UpdateScore(5, 10).

🔍 Worked example — Exam-style

A function is defined as FUNCTION GetTotal(Price : REAL, Tax : REAL) RETURNS REAL. If it is called as Total <- GetTotal(19.99, 1.50), identify the interface and the return value.

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

FUNCTION CalculateDiscount(Price : REAL, DiscountRate : REAL) RETURNS REAL

Key ideas — 11.3 (e) Writing efficient pseudocode

🧑‍🏫 Teacher's explanation

Writing efficient pseudocode is like planning a journey. If you need to go to the shops every day, you don't redraw the entire map every single morning; you just refer to the map you already have. In programming, 'efficiency' means reducing the number of operations the computer has to perform to get the correct answer.

📖 Definitions

🔍 Worked example — Easy

Write efficient pseudocode to find if a specific number X exists in an array of N integers. The array is called LIST.

🔍 Worked example — Standard

Rewrite this inefficient pseudocode to be efficient:

🔍 Worked example — Exam-style

A function calculateArea(radius) is needed. Write the pseudocode for the function header and the return statement using π = 3.14.

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

Identify one way the programmer could make the algorithm more efficient by using a function, and write the pseudocode for the function header and the return statement. [3 marks]

Worked example

Write a function IsValidCode(Code : STRING) RETURNS BOOLEAN that returns TRUE if Code is exactly 6 characters, where the first two are capital letters and the last four are digits.

🔍 Worked example — Easy

Write a function GetSquare(Num : INTEGER) RETURNS INTEGER that returns the square of a number.

🔍 Worked example — Standard

Trace the following pseudocode for input X = 15:\n\nFUNCTION Check(N : INTEGER) RETURNS BOOLEAN\n\tIF N MOD 5 = 0 THEN\n\t\tRETURN TRUE\n\tELSE\n\t\tRETURN FALSE\n\tENDIF\nENDFUNCTION\n\nOUTPUT Check(X)

🔍 Worked example — Exam-style

A function IsEven(N : INTEGER) RETURNS BOOLEAN is used. If we call IF IsEven(7) THEN OUTPUT 'Yes' ELSE OUTPUT 'No' ENDIF, what is the output?

⚠️ Common errors

Common mistakes

Practice

Answers: (1) The value is used in several places but does not change while the program runs; if the class size changes, only one line is edited, and the name makes the code clearer. (2) (a) "PUT"; (b) 2; (c) 7. (3) CASE OF Day / 6 : OUTPUT "Saturday" / 7 : OUTPUT "Sunday" / OTHERWISE : OUTPUT "Weekday" / ENDCASE. (4) The first number entered might be −1, so the loop body must be able to run zero times; the condition is tested before each repetition. (5) PROCEDURE Increase(BYREF Value : INTEGER, Amount : INTEGER) / Value ← Value + Amount / ENDPROCEDURE. Because Value is passed by reference, the change is made to the original variable in the calling code. (6) A parameter is the variable named in the subroutine header; an argument is the actual value passed when the subroutine is called.

Summary

All chapters in Algorithms, Data Structures and Programming

  1. 9 Algorithm Design and Problem-Solving
  2. 10 Data Types and Structures
  3. 11 Programming