Ch 1 · 8.1 Programming Concepts: Variables, Data Types, Selection and Iteration · O Level Computer Science 2210
Topic 1 of 4 in Programming — O Level Computer Science 2210 — 89 lessons.
Introduction
Every program is built from the same few ideas: store data in variables, input and output it, and control the flow of instructions with sequence, selection and iteration. This lesson shows each one in Cambridge pseudocode and in Python. (Syllabus section 8.1, outcomes 1–5.)
Key ideas — Variables and constants
A variable is a named storage location whose value can change while the program runs. A constant is a named value that does not change (e.g. a tax rate); using constants makes code easier to read and to update.
🧑🏫 Teacher's explanation
Imagine you are playing a video game. Your 'Score' is a variable; it starts at 0, but as you collect coins, that number changes constantly. However, the 'Gravity' setting in the game engine is a constant; it stays at 9.8 m/s^2 throughout the entire level to ensure the physics remain consistent. If you wanted to change how heavy everything feels, you would only change that one constant value at the top of the code, rather than hunting through thousands of lines of code to update every single jump calculation.
📖 Definitions
🔍 Worked example — Easy
A program uses a constant TAX_RATE set to 0.15. A variable totalPrice is initialized to 100. Calculate the new value of totalPrice after applying the tax.
🔍 Worked example — Standard
Trace the following pseudocode:
🔍 Worked example — Exam-style
A sensor records temperature. A constant MAX_TEMP is 50. A variable currentTemp is set to 45. If currentTemp increases by 6, what is the value of currentTemp and is it greater than MAX_TEMP?
⚠️ Common errors
🧠 Quick check 1
🧠 Quick check 2
🎯 Exam question
(a) Identify whether 'sales tax' should be declared as a variable or a constant. [1] (b) Write pseudocode to declare the sales tax and a variable for the total price, then assign the sales tax a value of 0.15 and the total price a value of 0.0. [3] [4 marks]
Key ideas — Data types
Choose the type that fits the data: a price is REAL; a count is INTEGER; a yes/no flag is BOOLEAN; a phone number is a STRING (it may start with 0 and is not used in calculations).
🧑🏫 Teacher's explanation
Imagine you are organizing a massive warehouse. You cannot put a heavy liquid in a cardboard box, and you cannot put a tiny screw in a giant shipping container without it getting lost. In programming, data types are like the specific containers designed for specific types of 'stuff'. If you try to put a decimal number into a container meant only for whole numbers, the computer gets confused or loses information.
📖 Definitions
🔍 Worked example — Easy
Identify the most appropriate data type for the following:
🔍 Worked example — Standard
A program stores a student's exam score as an INTEGER and their average grade as a REAL. If the score is 85 and the weight is 0.5, calculate the average grade.
🔍 Worked example — Exam-style
A programmer uses a STRING to store a phone number: "07712345678". Why is STRING a better choice than INTEGER for this specific data?
⚠️ Common errors
🧠 Quick check 1
🧠 Quick check 2
🎯 Exam question
(a) The number of books currently on a shelf. (b) The price of a book. (c) The first letter of a book's title. [3 marks]
Key ideas — Input and output
(In Python, input() returns a string; use int() or float() to convert numbers: age = int(input("Age: ")).)
🧑🏫 Teacher's explanation
Think of a computer program like a recipe. Before you start cooking, you need ingredients (data) and containers to hold them (variables). Input is like taking an ingredient from your pantry, and Output is like serving the finished dish to a guest.
📖 Definitions
🔍 Worked example — Easy
Trace the following pseudocode:
🔍 Worked example — Standard
A program needs to calculate the area of a rectangle. The user inputs the length and width. Write the pseudocode to perform this calculation and output the result.
🔍 Worked example — Exam-style
A program asks for a temperature in Celsius and converts it to Fahrenheit. The formula is F arrow (C × 9/5) + 32. Write the pseudocode to implement this.
⚠️ Common errors
🧠 Quick check 1
🧠 Quick check 2
🎯 Exam question
Key ideas — Sequence
Sequence means instructions are carried out one after another, in order.
🧑🏫 Teacher's explanation
Imagine you are following a recipe to bake a cake. You cannot frost the cake before you have mixed the ingredients, and you cannot mix the ingredients before you have cracked the eggs. If you change the order of these steps, the cake will fail. In programming, this 'order of operations' is called sequence.
📖 Definitions
🔍 Worked example — Easy
Trace the following pseudocode sequence and determine the final value of Total:
🔍 Worked example — Standard
A program calculates the area of a rectangle. The sequence is:
🔍 Worked example — Exam-style
Identify the error in the following sequence and provide the corrected value of Result:
⚠️ Common errors
🧠 Quick check 1
🧠 Quick check 2
🎯 Exam question
DECLARE Total : INTEGER DECLARE Count : INTEGER Total arrow 0 Count arrow 0
Key ideas — Selection
Selection chooses which instructions to run, depending on a condition.
🧑🏫 Teacher's explanation
Imagine you are standing at a crossroads with several signs pointing to different destinations. You don't just walk blindly; you look at the sign (the condition) and decide which path to take. In programming, selection is that decision-making process. It allows a program to behave differently depending on whether a condition is true or false.
📖 Definitions
🔍 Worked example — Easy
A program uses an IF statement to check if a student's score S is 50 or more. If S ≥ 50, output "Pass", otherwise output "Fail". Trace the output for S = 45.
🔍 Worked example — Standard
A program uses a CASE statement to map a grade character to a description. CASE OF Grade 'A' : OUTPUT "Excellent" 'B' : OUTPUT "Good" OTHERWISE OUTPUT "Needs Improvement" ENDCASE
🔍 Worked example — Exam-style
A program uses nested selection. IF Age < 18 THEN IF HasParentalConsent = TRUE THEN OUTPUT "Allowed" ELSE OUTPUT "Not Allowed" ENDIF ELSE OUTPUT "Adult" ENDIF
⚠️ Common errors
🧠 Quick check 1
🧠 Quick check 2
🎯 Exam question
If the temperature is less than 18, it outputs "Heating On". If the temperature is between 18 and 25 (inclusive), it outputs "Eco Mode". If the temperature is greater than 25, it outputs "Cooling On".
Key ideas — Iteration (loops)
(Python has no REPEAT…UNTIL; use while True: with break when the condition is met.)
🧑🏫 Teacher's explanation
Iteration is simply the process of repeating a set of instructions multiple times. Think of it like a track athlete running laps. If the coach says, "Run exactly 5 laps," you know exactly when you will finish before you even start—this is a count-controlled loop. If the coach says, "Run until you feel tired," you don't know how many laps you will do, and you might stop before you even start if you are already exhausted—this is a pre-condition loop. If the coach says, "Run one lap, then check if you are tired," you are guaranteed to run at least one lap before checking—this is a post-condition loop.
📖 Definitions
🔍 Worked example — Easy
Trace the following pseudocode and determine the final value of Total:
🔍 Worked example — Standard
A program uses a WHILE loop to sum numbers entered by a user until the user enters 0. Trace the execution if the inputs are 5, 12, 7, and 0.
🔍 Worked example — Exam-style
An exam-style question: A programmer uses a REPEAT...UNTIL loop to validate a password. The user enters 'wrong', then 'wrong', then 'Secret'. How many times does the loop body execute?
⚠️ Common errors
🧠 Quick check 1
🧠 Quick check 2
🎯 Exam question
Write pseudocode using a pre-condition loop to implement this logic. The program should output the average of the numbers entered (excluding the negative number). [4 marks]
Key ideas — Totalling and counting
🧑🏫 Teacher's explanation
Imagine you are a teacher grading a stack of 10 exam papers. To keep track of the results, you need two different tools: a tally sheet and a calculator. The tally sheet is for 'counting'—every time you see a student passed, you add a mark to your tally. The calculator is for 'totalling'—every time you see a score, you add that specific number to a running sum to find the average later.
📖 Definitions
🔍 Worked example — Easy
A program uses a loop to input 5 integers. It counts how many integers are negative. Trace the value of Count if the inputs are 10, -5, 0, -2, 7.
🔍 Worked example — Standard
Calculate the final value of Total and Count for the following pseudocode: Total \leftarrow 0 Count \leftarrow 0 FOR i \leftarrow 1 TO 4 INPUT x Total \leftarrow Total + x IF x > 10 THEN Count \leftarrow Count + 1 ENDIF NEXT i Inputs: 5, 15, 10, 20
🔍 Worked example — Exam-style
A program inputs n numbers. It calculates the sum of all numbers and the count of numbers that are even. If the inputs are 3, 8, 12, 7, 2, what is the final Total and Count?
⚠️ Common errors
🧠 Quick check 1
🧠 Quick check 2
🎯 Exam question
Write pseudocode to implement this logic. [4] [4 marks]
Key ideas — Nested statements
A nested statement is one inside another: an IF inside a loop, a loop inside a loop, or an IF inside an IF. You will not need more than three levels of nesting.
🧑🏫 Teacher's explanation
Imagine you are organizing a large school assembly. First, you decide which hall to use (Level 1). Once you are in the hall, you decide which row of seats to look at (Level 2). Once you have picked a row, you look at each individual student in that row one by one (Level 3). Each decision depends on the one before it. This is exactly how nested statements work.
📖 Definitions
🔍 Worked example — Easy
Trace the following pseudocode and determine the final value of Total:
🔍 Worked example — Standard
A program uses a nested IF statement to check a student's score. IF score > 50 THEN IF score > 80 THEN OUTPUT "Grade A" ELSE OUTPUT "Grade B" ENDIF ELSE OUTPUT "Fail" ENDIF
🔍 Worked example — Exam-style
A grid of 2 × 2 cells is being processed. Each cell (r, c) contains the value r + c. Calculate the sum of all cell values using nested loops where r is the row index (1 to 2) and c is the column index (1 to 2).
⚠️ Common errors
🧠 Quick check 1
🧠 Quick check 2
🎯 Exam question
Worked example
Write an algorithm that keeps asking for a password until "CodeArc123" is entered, then outputs how many attempts were made.
🔍 Worked example — Easy
Trace the following pseudocode: DECLARE x : INTEGER DECLARE y : INTEGER x arrow 5 y arrow 2 WHILE x < 12 x arrow x + y y arrow y + 1 ENDWHILE OUTPUT x
🔍 Worked example — Standard
A program uses a REPEAT loop to sum numbers entered by a user. The loop ends when the user enters -1. If the user enters 5, 10, 3, -1, what is the final total?
🔍 Worked example — Exam-style
Convert the following logic to a truth table: IF (A AND B) OR (NOT C) THEN OUTPUT 'Yes' ELSE OUTPUT 'No'. What is the output when A=True, B=False, C=False?
⚠️ Common errors
Common mistakes
Practice
Answers: (1) (a) STRING; (b) REAL; (c) BOOLEAN; (d) INTEGER. (2) A pre-condition loop tests the condition before each repetition and may not run at all; a post-condition loop tests it after, so it always runs at least once. (3) CASE OF Day / 1 : OUTPUT "Monday" / 2 : OUTPUT "Tuesday" / 3 : OUTPUT "Wednesday" / OTHERWISE OUTPUT "Unknown" / ENDCASE. (4) FOR Count ← 1 TO 12 / OUTPUT "7 x ", Count, " = ", 7 * Count / NEXT Count.