Ch 2 · 8.1 Programming Concepts: Strings, Operators, Subroutines and Maintainable Code · O Level Computer Science 2210

Topic 2 of 4 in Programming — O Level Computer Science 2210 — 69 lessons.

Introduction

Real programs work with text, do calculations, and are split into reusable pieces called subroutines. Writing them clearly, so others can maintain them, matters as much as making them work. (Syllabus section 8.1, outcomes 4(e), 4(f), 6–8.)

Key ideas — String handling

In Cambridge pseudocode, the first character is usually at position 1. (Python counts from 0: "Happy Days"[0:5] is "Happy"; len(), .upper(), .lower().)

🧑‍🏫 Teacher's explanation

Think of a string as a beaded necklace where each bead represents a single character. If you want to know how long the necklace is, you count the beads. If you want to grab a specific section of beads from the middle, you need to know exactly where to start and how many beads to take.

📖 Definitions

🔍 Worked example — Easy

Given the string $S \leftarrow \text{"Computer"}$, find the result of LENGTH(S).

🔍 Worked example — Standard

Given the string $S \leftarrow \text{"Algorithm"}$, find the result of SUBSTRING(S, 3, 4).

🔍 Worked example — Exam-style

A program takes a user input U. If $U \leftarrow \text{"Data"}$, what is the result of UCASE(LCASE(U))?

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

Key ideas — Operators

Arithmetic: +, -, *, /, ^ (raised to the power of), and integer division:

🧑‍🏫 Teacher's explanation

Think of operators as the 'verbs' of programming. If variables are nouns (the things we are talking about), operators are the actions we perform on them. Without operators, a program is just a static list of data; with them, it becomes a dynamic engine that can calculate, compare, and make decisions.

📖 Definitions

🔍 Worked example — Easy

Calculate the result of 25 ext MOD 4 and 25 ext DIV 4.

🔍 Worked example — Standard

Evaluate the Boolean expression: (15 < 10) ext OR (20 ≠ 20) ext AND extNOT (5 = 5)

🔍 Worked example — Exam-style

A program uses the following logic to check if a user can access a file: \nIF (UserType = "Admin") OR (UserType = "Guest" AND AccessLevel > 5) THEN OUTPUT "Access Granted" ELSE OUTPUT "Access Denied" ENDIF. \nWhat is the output if UserType is "Guest" and AccessLevel is 3?

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

Key ideas — Procedures and functions

A subroutine is a named block of code that does a specific task and can be called whenever it is needed.

🧑‍🏫 Teacher's explanation

Imagine you are following a recipe to bake a cake. Instead of writing 'crack an egg, whisk it, pour it into the bowl' every single time you need eggs, you just write a single instruction called 'PrepareEggs'. Whenever the recipe says 'PrepareEggs', you follow those specific steps. In programming, this 'instruction' is a subroutine.

📖 Definitions

🔍 Worked example — Easy

A procedure GreetUser(Name : STRING) is defined. It outputs 'Hello ' followed by the value of Name. Trace the output of the following code:

🔍 Worked example — Standard

A function CalculateTax(Price : REAL) RETURNS REAL is defined as:

🔍 Worked example — Exam-style

Consider the following pseudocode:

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

(a) Write the pseudocode for the function CalculateDiscount. (b) Explain one advantage of using a function instead of writing the discount calculation multiple times throughout the program. [3 marks]

Key ideas — Local and global variables

Local variables are safer: they cannot be changed accidentally by other parts of the program, and the same name can be reused in different subroutines.

🧑‍🏫 Teacher's explanation

Imagine you are organizing a large school festival. A global variable is like the school's main announcement system; anyone in the school can hear it and anyone with a microphone can change what is being said. It is accessible to everyone, but if someone makes a mistake, the whole school is affected.

📖 Definitions

🔍 Worked example — Easy

Consider a program with a global variable X set to 10. A procedure Calculate is called. Inside Calculate, a local variable Y is set to 5. The procedure then performs X arrow X + Y. What is the value of X after the procedure finishes?

🔍 Worked example — Standard

A program has a global variable Score initialized to 0. Two subroutines are called: AddPoints() and ResetScore(). AddPoints() contains a local variable Bonus set to 5, and it executes Score <- Score + Bonus. ResetScore() sets Score <- 0. What is the value of Score after both subroutines have executed in sequence?

🔍 Worked example — Exam-style

A programmer uses a global variable Counter to track loops. In a subroutine ProcessData(), they declare a local variable Counter and set it to 1. They then perform Counter <- Counter + 1. What is the value of the global Counter after ProcessData() completes if the global Counter was initially 10?

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

(a) State one advantage of using the local variable StudentScore instead of making it a global variable. [1] (b) Explain why using too many global variables can make a program difficult to maintain. [2] [3 marks]

Key ideas — Library routines

Library routines are ready-made, tested subroutines provided by the language:

🧑‍🏫 Teacher's explanation

Imagine you are building a complex LEGO castle. You could spend hours carving every single tiny brick from wood yourself, or you could just open a box of pre-made LEGO bricks that are already perfectly shaped and tested. In programming, library routines are those pre-made bricks. Instead of writing complex mathematical formulas or logic to find a remainder or generate a random number, you use a 'ready-made' function provided by the language.

📖 Definitions

🔍 Worked example — Easy

Calculate the result of MOD(25, 4) and DIV(25, 4).

🔍 Worked example — Standard

A program uses ROUND(3.14159, 3). What is the output?

🔍 Worked example — Exam-style

An algorithm needs to generate a random integer between 1 and 10 inclusive using RANDOM(). Write the expression using ROUND and RANDOM().

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

Calculate the value of DIV(50, 6). [2 marks]

Key ideas — Maintainable programs

A maintainable program is easy for someone else (or you, later) to understand, correct and update. Use:

🧑‍🏫 Teacher's explanation

Imagine you are building a massive LEGO castle. If you throw all the bricks into one giant pile without instructions, you might build something, but if a piece breaks or you want to add a tower later, you will struggle to find anything. A maintainable program is like having a well-organized instruction manual where every brick type is in its own labeled bin.

📖 Definitions

🔍 Worked example — Easy

Identify the non-maintainable elements in this pseudocode snippet:

🔍 Worked example — Standard

Rewrite the following code to be maintainable using meaningful identifiers and a procedure:

🔍 Worked example — Exam-style

A programmer uses a global variable 'g' to store the current user's score. They write a function 'update()' that changes 'g'. Explain why this is poor practice for maintainability.

⚠️ Common errors

🧠 Quick check 1

🧠 Quick check 2

🎯 Exam question

DECLARE x : INTEGER DECLARE y : INTEGER x <- 50 y <- 10 x <- x + y OUTPUT x [3 marks]

Worked example

Write a function IsEven that takes an integer and returns TRUE if it is even, then use it to output whether 14 is even.

🔍 Worked example — Easy

Write a function Square that takes an integer n and returns its square (n^2). Call it with the value 5.

🔍 Worked example — Standard

A function CheckLength takes a string and returns TRUE if the length is greater than 5, otherwise FALSE. Trace the result for the input "Hello".

🔍 Worked example — Exam-style

A program uses a global variable Total initialized to 0. A procedure AddValue(n : INTEGER) is called with n = 10, then n = 5. What is the final value of Total? Assume AddValue adds n to Total.

⚠️ Common errors

Common mistakes

Practice

Answers: (1) (a) 7; (b) "put"; (c) "PAK". (2) 5 and 3. (3) A function returns a value and is used in an expression; a procedure does not return a value and is called with CALL. (4) A local variable is declared in a subroutine and can only be used there; a global variable is declared in the main program and can be used anywhere. (5) Any three: meaningful identifiers; comments; procedures and functions; consistent indentation.

Summary

All chapters in Programming

  1. 8.1 Programming Concepts: Variables, Data Types, Selection and Iteration
  2. 8.1 Programming Concepts: Strings, Operators, Subroutines and Maintainable Code
  3. 8.2 Arrays
  4. 8.3 File Handling