A Level Computer Science · Chapter 20 · Component 02: Algorithms and programming
Every program, however large, is built from three constructs, sequence, selection and iteration, working on variables, operators and strings.
This chapter teaches the building blocks you write in every programming question. You will use DIV and MOD, write IF and CASE statements, choose between count-controlled and condition-controlled loops, handle strings, and trace programs by hand with a trace table.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- use variables, constants, data types and the arithmetic, relational and Boolean operators, including DIV and MOD
- write and trace selection with IF, ELSEIF, ELSE, nested IF and CASE
- write and trace count-controlled loops, including steps and nested loops
- write and trace condition-controlled loops, and choose between WHILE and REPEAT UNTIL
- manipulate strings with length, substring, left, right, ASC and CHR
- validate input with a loop and read and write text files
- complete a trace table for an unfamiliar algorithm
Time: three sessions, about 4 hours, plus the programming task.
You need first: the idea of an algorithm from Computational thinking, and character codes from Number systems and binary arithmetic.
The big picture
The big picture
A cash machine asks for your PIN. If it is wrong, it asks again, up to three times. If it is right, it shows a menu and waits for a choice. It counts out the notes, one at a time, and prints a receipt line by line. Every step of that is one of three ideas.
Sequence means doing steps in order, one after another. Selection means choosing between paths, such as checking whether the PIN is right. Iteration means repeating, such as counting out notes or asking again. These three constructs are enough to write any algorithm a computer can carry out.
The constructs work on data held in variables. A variable is a named location in memory whose value can change as the program runs. Operators combine values: arithmetic operators calculate, relational operators compare and Boolean operators join conditions.
Much of the data people care about is text. Names, passwords and messages are strings, and programs constantly cut them up, join them and compare them. A string is just a sequence of character codes, so string handling is closely linked to the binary codes of Number systems and binary arithmetic.
The skill that ties this chapter together is tracing. A trace table records the value of every variable after each step. It is how you find out what an unfamiliar program does, and how you find the bug in one that does not work. Exam papers ask for trace tables on almost every algorithm.
Two operators deserve special attention, because they turn up everywhere: DIV and MOD. DIV gives the whole-number part of a division, and MOD gives the remainder. Together they split numbers into digits, convert units, test for even numbers and wrap values round, as in a clock.
Exam questions are written in pseudocode, a plain, language-neutral way of writing algorithms. You may answer in pseudocode or in a real language such as Python. The constructs are the same in every language; only the spelling changes. This chapter shows both, so you can move between them easily.
Section 1
Sequence, variables and operators
Variables and constants
A variable is a named store for a value that can change. A constant is a named value that is fixed when the program is written and cannot change while it runs. Using a constant, such as VAT_RATE = 0.2, makes a program easier to read and to update, because the value is changed in one place.
Each variable has a data type, which decides what values it can hold and what can be done with it. The main types are integer, real (or float), Boolean, character and string. Casting converts between them, for example int("42") turns the string "42" into the integer 42.
Choosing a data type
The data type should match what the value means. A count of pupils is an integer, because there is no such thing as half a pupil. A price or a temperature is a real number. A yes-or-no answer is a Boolean, and a name is a string, even when it looks like a number, such as a phone number.
Phone numbers show why the choice matters. Stored as an integer, 07700 900123 would lose its leading zero, and nobody ever adds two phone numbers together. Data that is only ever compared or displayed, never calculated with, is usually best kept as a string.
Real numbers are stored in binary floating point, so many decimals cannot be held exactly. In Python, 0.1 + 0.2 gives 0.30000000000000004. Programs that handle money often store whole pence as integers instead, so that every total is exact.
Arithmetic operators
The arithmetic operators are +, −, *, / and ^, for addition, subtraction, multiplication, division and powers. Division with / gives a real answer, so 17 / 5 is 3.4. Two more operators work only on whole numbers, and they are some of the most useful in programming.
DIV gives the quotient of a whole-number division: how many whole times one number goes into another. MOD gives the remainder that is left over. So 17 DIV 5 = 3 and 17 MOD 5 = 2, because 5 goes into 17 three times with 2 left over. In Python these are // and %.
Common mistake: confusing DIV with ordinary division. DIV throws away the remainder, so 17 DIV 5 is 3, not 3.4. Using / where DIV is needed gives a real number, which then fails as an array index or a count of whole items.
Worked example 1: converting minutes
A film lasts 200 minutes. Use DIV and MOD to give its length in hours and minutes.
| Working | Reason |
|---|---|
| hours = 200 DIV 60 = 3 | 60 goes into 200 three whole times |
| 3 × 60 = 180 minutes are used up | Check how much the whole hours cover |
| minutes = 200 MOD 60 = 20 | The remainder after taking out whole hours |
| The film lasts 3 hours 20 minutes | Combine the quotient and the remainder |
Worked example 2: splitting off digits
Use DIV and MOD to split off the last digit of 4725, and the number that is left.
| Working | Reason |
|---|---|
| 4725 MOD 10 = 5 | The remainder after dividing by 10 is the last digit |
| 4725 DIV 10 = 472 | Dividing by 10 and dropping the remainder removes that digit |
| Repeating on 472 gives the digit 2 and leaves 47 | The same two steps work on what is left |
| The digits come out in reverse order: 5, 2, 7, 4 | MOD 10 always takes the rightmost digit |
Operator precedence
When an expression mixes operators, they are applied in a fixed order of precedence. Brackets come first, then powers, then multiplication, division, DIV and MOD, and finally addition and subtraction. So 2 + 3 * 4 is 14, not 20, and (2 + 3) * 4 is 20.
When in doubt, add brackets. They cost nothing, and they make the intended order obvious to anyone reading the code, including you a month later.
Relational and Boolean operators
Relational operators compare two values and give a Boolean result: == (equal to), != (not equal to), <, <=, > and >=. Note that a single = means assignment, while == means comparison. Mixing them up is one of the commonest errors in code.
Boolean operators join conditions. AND is true only if both sides are true. OR is true if at least one side is true. NOT reverses a condition. So age >= 13 AND age <= 19 is true only for teenagers, while day == "Sat" OR day == "Sun" is true at the weekend.
Assignment and swapping
Assignment works from right to left: the expression on the right is worked out first, then stored in the variable on the left. That is why count = count + 1 makes sense. It reads the old value of count, adds 1, and stores the result back in count.
Swapping two variables needs care. Writing a = b then b = a leaves both holding b's old value, because a's value was overwritten first. The usual fix uses a temporary variable: temp = a, then a = b, then b = temp. Python can also swap in one line with a, b = b, a.
DIV and MOD in everyday algorithms
MOD appears whenever values go round in a cycle. The day of the week 10 days after a Wednesday is found with (3 + 10) MOD 7, counting Monday as 0. A circular queue moves its pointer with (rear + 1) MOD size. Checking whether a number divides exactly by another is simply a test of whether the MOD is 0.
DIV appears whenever things are grouped. Seating 47 pupils in rows of 6 fills 47 DIV 6 = 7 complete rows, with 47 MOD 6 = 5 pupils in a final, shorter row. Most unit conversions, such as seconds into minutes, use both operators together.
Check yourself. Find 47 DIV 6 and 47 MOD 6, and say how they could be used to check the answer.
Show the answer
47 DIV 6 = 7 and 47 MOD 6 = 5, because 6 × 7 = 42 and 47 − 42 = 5. They check each other: 6 × 7 + 5 must give back 47.
Section 2
Selection
IF, ELSEIF and ELSE
Selection lets a program choose what to do. An IF statement tests a condition. If it is true, one block of code runs. If it is false, that block is skipped, and an optional ELSE block runs instead. Only one branch ever runs.
if mark >= 70 then
grade = "A"
elseif mark >= 60 then
grade = "B"
elseif mark >= 50 then
grade = "C"
else
grade = "U"
endif
An ELSEIF chain tests its conditions in order, from the top. The first one that is true decides the branch, and every condition below it is skipped. That makes the order of the tests part of the meaning of the program.
Common mistake: ordering an ELSEIF chain from the bottom up. If the chain tests mark >= 50 before mark >= 70, a mark of 85 stops at the first test and gets a C. Put the narrowest or highest test first, so each mark reaches the branch it belongs in.
Figure 20.1 runs a grading chain on any mark you choose. Follow which test succeeds and which are never tested. Then switch on the wrong model, which writes the tests from the bottom up.
The order of an IF … ELSEIF chain
- Grade
- B
- Conditions tested
- 2
Worked example 3: tracing an ELSEIF chain
Use the grading code above to find the grade for a mark of 65, and count how many conditions are tested.
| Working | Reason |
|---|---|
| Test mark >= 70: 65 >= 70 is false | The first condition fails, so move on |
| Test mark >= 60: 65 >= 60 is true, so grade = "B" | The first true condition decides the branch |
| The test mark >= 50 is never made | ELSEIF stops at the first true branch |
| Grade B, after 2 conditions | Later tests are skipped entirely |
Compound conditions and nested IF
A condition can combine several tests with AND, OR and NOT. A nested IF puts one IF inside another, so the inner test is only made when the outer one is true. Nesting is useful when the second question only makes sense after the first, but deep nesting is hard to read.
Common mistake: using AND where OR is needed. A day cannot be both "Sat" and "Sun", so day == "Sat" AND day == "Sun" is always false. When either of two values should be accepted, the conditions must be joined with OR.
Worked example 4: a compound condition
A year is a leap year if it divides by 4 but not by 100, unless it also divides by 400. Decide whether 1900 and 2000 are leap years.
| Working | Reason |
|---|---|
| Condition: (year MOD 4 == 0 AND year MOD 100 != 0) OR year MOD 400 == 0 | The rule written with Boolean operators |
| 1900: divides by 4 and by 100, so the first part is false | 1900 MOD 100 = 0 breaks the AND |
| 1900 MOD 400 = 300, so the second part is false too: not a leap year | Both sides of the OR are false |
| 2000 MOD 400 = 0, so 2000 is a leap year | One true side makes the OR true |
Short-circuit evaluation
Most languages stop evaluating a condition as soon as the answer is known. In a AND b, if a is false, b is never checked, because the whole condition must be false. In a OR b, if a is true, b is skipped. This is called short-circuit evaluation.
It can be used on purpose to avoid errors. The condition i < len(names) AND names[i] == "Asha" checks the index first. If i is past the end of the array, the second test, which would crash, is never made.
CASE statements
When one variable is compared with many fixed values, a CASE (or switch) statement is clearer than a long ELSEIF chain. Each case lists a value and the code to run, and a default case catches anything else. Python 3.10 provides match for the same job.
switch choice:
case "1":
showBalance()
case "2":
withdrawCash()
default:
print("Unknown option")
endswitch
Nested IFs and ELSEIF chains can often express the same logic. An ELSEIF chain is flatter and easier to read when the tests are alternatives on one value. Nesting is clearer when a second question only makes sense after the first, such as checking a password only once the username has been found.
Testing selection
Every branch of a selection statement needs at least one test. For a grading chain, that means a mark in each grade band, and a mark that gets U. The most important tests sit on the boundaries, such as 69, 70 and 71, because that is where a wrong operator, such as > instead of >=, shows up.
Check yourself. Suppose a grading chain tests mark >= 40 first, then mark >= 70. What grade does a mark of 90 get, and why?
Show the answer
It gets the grade for mark >= 40, because 90 >= 40 is true and the chain stops at the first true condition. The test mark >= 70 is never reached, so the higher test must come first.
Section 3
Count-controlled iteration
FOR loops
A count-controlled loop repeats a set number of times. In exam pseudocode, for i = 1 to 10 runs its body ten times, with i taking the values 1, 2 and so on up to 10. The loop variable can be used inside the body, for example as an array index.
A step changes how far i moves each time. for i = 1 to 10 step 3 gives 1, 4, 7 and 10. A negative step counts down: for i = 10 to 0 step −2 gives 10, 8, 6, 4, 2 and 0. If the start is already past the end, the body never runs.
Common mistake: thinking the loop stops before its end value. In exam pseudocode, for i = 1 to 10 includes 10. Python's range(1, 10) stops at 9, so translating between them needs care. Getting this wrong is called an off-by-one error.
Figure 20.2 marks every value a FOR loop gives its variable. Change the start, end and step, and count the passes. Then switch on the wrong model, which stops before the end value.
A count-controlled loop
- Values of i
- 1, 4, 7, 10
- Passes
- 4
- i after the loop
- 13
Worked example 5: a loop with a step
How many times does the body of for i = 1 to 10 step 3 run, and what is i on each pass?
| Working | Reason |
|---|---|
| i starts at 1, then 4, then 7 | Each pass adds the step, 3 |
| The next value is 10, which equals the end, so it runs | The end value is included when reached |
| The next value would be 13, past the end, so the loop stops | 13 is greater than the end value |
| Values 1, 4, 7, 10: the body runs 4 times | One pass for each value |
Derivation: how many passes a FOR loop makes
On pass k, the loop variable has been increased by the step k − 1 times. So its value is the start plus k − 1 steps.
The pass runs only while this value has not passed the end. Rearranging the condition i_k ≤ end gives the largest k, which is the number of passes.
For start 1, end 10 and step 3, that is ⌊9 ÷ 3⌋ + 1 = 4 passes. For start 1, end 11 and step 3, it is ⌊10 ÷ 3⌋ + 1 = 4 again, because 13 would overshoot.
Common loop patterns
A handful of patterns appear inside loops again and again. A counter adds 1 each time something happens, such as counting the pupils who passed. An accumulator adds a value to a running total, such as summing the marks. Dividing the total by the count afterwards gives the mean.
A maximum or minimum is found by keeping the best value so far. Start with the first item, then compare every later item with it, replacing it whenever a better one appears. Starting with 0 instead is a classic error, because it fails when every value is negative.
Changing the loop variable inside the body of a FOR loop is poor practice. In some languages it changes how many passes happen; in others it is ignored. Either way the code becomes confusing. If the number of passes needs to change, a WHILE loop is the honest choice.
Python also has a "for each" loop, for name in names, which visits every item without needing an index. It is shorter and avoids off-by-one errors. When the position of each item matters, a counting loop over the indices is still needed.
FOR loops in Python
Python's for loop is written with range. The call range(1, 11) gives 1 to 10, because Python stops before its second argument, and range(1, 11, 3) gives 1, 4, 7 and 10. So the pseudocode loop for i = a to b becomes for i in range(a, b + 1) in Python. Remembering that + 1 is the whole trick of translating between the two.
A negative step works in the same way: range(10, -1, -2) counts down 10, 8, 6, 4, 2, 0. The second argument, −1, is one past the last value wanted, in the direction of travel.
Nested loops
A loop inside another loop is a nested loop. The inner loop runs completely for every pass of the outer loop. Nested loops suit two-dimensional work, such as visiting every cell of a grid or comparing every pair of items.
Worked example 6: counting nested passes
How many times does the inner body run when an outer loop of 4 passes contains an inner loop of 6 passes? How many if the inner loop runs from 1 to i, for i = 1 to 10?
| Working | Reason |
|---|---|
| The inner loop runs 6 times for each outer pass | It restarts on every outer pass |
| 4 × 6 = 24 inner passes | Multiply the passes of the two loops |
| With j = 1 to i, the inner loop runs 1, 2, 3 … 10 times | Its length grows with i |
| 1 + 2 + … + 10 = 10 × 11 ÷ 2 = 55 passes | The sum of a triangle of passes |
Loops over arrays
A FOR loop is the natural way to visit every element of an array. For an array of n elements, numbered from 0, the loop runs for i = 0 to n − 1. Writing n instead of n − 1 reads one element past the end, which is the most common off-by-one error of all.
Looping backwards, for i = n − 1 to 0 step −1, visits the elements in reverse order. That is useful for printing a list backwards, or for removing items from an array without skipping any of them.
Check yourself. List the values of i given by for i = 20 to 5 step −5.
Show the answer
i takes 20, 15, 10 and 5. The step is negative, so the loop counts down, and 5 is included because it equals the end value. The next value, 0, is past the end, so the loop stops.
Section 4
Condition-controlled iteration
WHILE loops
A condition-controlled loop repeats until a condition changes, which suits jobs where the number of passes is not known in advance. A WHILE loop tests its condition before each pass. If the condition is false at the start, the body never runs at all.
Something inside the body must eventually make the condition false. If nothing changes, the loop runs for ever: an infinite loop. In the digit loop below, n = n DIV 10 makes n smaller on every pass, so n must reach 0.
Common mistake: forgetting to change the loop variable. If the body of a WHILE loop never changes the variables in its condition, the condition stays true and the loop never ends. Check that every pass moves the program closer to stopping.
Worked example 7: a trace table for a WHILE loop
Trace this code for n = 4725, and give the output.
total = 0
while n > 0
total = total + n MOD 10
n = n DIV 10
endwhile
print(total)
| Working | Reason |
|---|---|
| Pass 1: total = 0 + 5 = 5, n = 472 | The last digit, 4725 MOD 10, is 5 |
| Pass 2: total = 7, n = 47; pass 3: total = 14, n = 4 | Each pass removes one digit |
| Pass 4: total = 18, n = 0 | The last digit is 4 |
| n > 0 is now false, so the loop ends and prints 18 | The condition fails after four passes |
Derivation: how many passes the digit loop makes
A number n with k digits lies between the smallest and largest k-digit numbers.
Each pass divides n by 10 and drops the remainder, removing one digit. So the loop makes one pass per digit. Taking logarithms of the inequality gives k directly.
For n = 4725, log₁₀ 4725 is about 3.67, so k = 3 + 1 = 4 passes. The loop's work grows with the number of digits, not with the size of n.
Worked example 8: Euclid's algorithm
Euclid's algorithm finds the highest common factor of two numbers. While b is not 0, it replaces a and b with b and a MOD b. Trace it for a = 252 and b = 105.
| Working | Reason |
|---|---|
| 252 MOD 105 = 42, so a = 105 and b = 42 | 105 goes in twice, making 210, leaving 42 |
| 105 MOD 42 = 21, so a = 42 and b = 21 | 42 goes in twice, making 84, leaving 21 |
| 42 MOD 21 = 0, so a = 21 and b = 0 | It divides into 42 exactly, leaving nothing |
| b is 0, so the loop stops: the answer is 21 | a holds the highest common factor |
Sentinels and flags
Sometimes a loop reads values until a special value appears, called a sentinel. A program might add up marks until the user types −1. The sentinel itself must not be added to the total, so the test must come before the value is used.
A flag is a Boolean variable that records whether something has happened. A search might set found = False before the loop, set it to True when the item is met, and use while NOT found AND i < n as its condition. Flags make the reason a loop stops easy to see.
Any FOR loop can be rewritten as a WHILE loop, by setting the counter before the loop and adding to it at the end of the body. The reverse is not always possible, because a FOR loop needs its number of passes in advance.
REPEAT UNTIL loops
A REPEAT UNTIL loop tests its condition after each pass, so its body always runs at least once. It stops when the condition becomes true, which is the opposite sense to WHILE. It suits jobs that must happen before they can be checked, such as asking for input.
Common mistake: thinking a REPEAT loop may run zero times. The condition of a REPEAT UNTIL loop is tested only at the end of each pass. Even when the condition is already true at the start, the body runs once before the test.
Python has no REPEAT UNTIL loop. The same effect is written as while True, with the body first and an if test that uses break to leave the loop. That pattern looks different, but it behaves exactly like a post-condition loop: the body always runs before the test.
Worked example 9: WHILE against REPEAT
value starts at 10, the step is 5 and the limit is 5. Compare a WHILE loop that runs while value < limit with a REPEAT loop that runs until value >= limit.
| Working | Reason |
|---|---|
| WHILE: test 10 < 5 first, which is false | A pre-condition loop tests before the body |
| The WHILE body runs 0 times and value stays 10 | The loop is skipped entirely |
| REPEAT: the body runs first, making value 15 | A post-condition loop always runs once |
| Test 15 >= 5 is true, so REPEAT stops after 1 pass | The test comes after the body |
Doing a dry run
A dry run means working through a program by hand, without a computer. Write a column for every variable, and one for the output. Then follow the code one line at a time, writing a new value each time a variable changes. Never guess what a loop will do; trace it pass by pass.
Dry runs find logic errors, where the program runs but gives the wrong answer. They are also the quickest way to understand someone else's code. If a trace table gets long, look for a pattern after a few rows, then check the final rows carefully.
Check yourself. A loop doubles a value from 3 until it reaches at least 100. How many passes does it make, and what is the final value?
Show the answer
The value goes 3, 6, 12, 24, 48, 96, 192. That is 6 doublings, and the loop stops once 192 is at least 100. So it makes 6 passes and the final value is 192.
Section 5
String handling
Strings as sequences
A string is a sequence of characters, each stored as a character code. The characters are numbered from 0, like an array, so in "COMPUTER" the C is at position 0 and the R is at position 7. The length is the number of characters, here 8.
The standard string operations are length, substring, left, right, upper and lower case, and concatenation with +. In exam pseudocode, word.substring(3, 4) takes 4 characters starting at position 3. In Python, the same is written as a slice, word[3:7].
Common mistake: counting string positions from 1. Strings are numbered from 0, so the first character is at position 0 and position 3 is the fourth character. Counting from 1 shifts every substring one place along and gives the wrong characters.
Worked example 10: substring, left and right
Find substring(3, 4), left(3) and right(3) of "COMPUTER".
| Working | Reason |
|---|---|
| substring(3, 4) starts at position 3, the P | Positions are counted from 0 |
| It takes 4 characters: P, U, T, E, giving "PUTE" | The second number is a length |
| left(3) is "COM", the first three characters | Left takes from the start |
| right(3) is "TER", the last three characters | Right takes from the end |
Joining and comparing strings
Concatenation joins strings with +, so "Ada" + " " + "Lovelace" gives "Ada Lovelace". Joining a number to a string usually needs the number cast first, as in "Score: " + str(42). Without the cast, many languages report a type error.
Strings are compared character by character, using their codes. So "apple" < "banana", because the code for a is less than the code for b. Capital letters have smaller codes than lower-case ones, so "Zebra" < "apple". Programs that sort names usually convert them to one case first.
In Python, strings are immutable: a string cannot be changed in place. Every operation that seems to change one, such as upper(), actually builds a new string. That is why the cipher in this chapter builds its result one character at a time.
Case conversion is another common step. Calling upper() turns every letter into a capital, which lets a program compare answers without caring how the user typed them. "yes", "Yes" and "YES" all become "YES". Many validation routines convert to one case before checking anything else.
Character codes
ASC returns the code of a character, and CHR turns a code back into a character. In ASCII and Unicode, A is 65, B is 66 and so on, and a is 97. Because the letters have consecutive codes, arithmetic on codes moves through the alphabet.
Worked example 11: a Caesar cipher
A Caesar cipher shifts each capital letter forward by k places, wrapping Z round to A. Encrypt ZEBRA with k = 3.
| Working | Reason |
|---|---|
| For each letter, position = ASC(letter) − 65 | This gives 0 for A up to 25 for Z |
| new = (position + 3) MOD 26, then CHR(new + 65) | MOD 26 wraps the alphabet round |
| Z is 25: (25 + 3) MOD 26 = 2, which is C | Z wraps round past A and B |
| E, B, R, A become H, E, U, D: the result is CHEUD | Every other letter simply moves on 3 |
Common mistake: forgetting to wrap round past Z. Adding 3 to the code of Z gives 93, which is the code of a bracket, not a letter. The shift must be done on positions 0 to 25 with MOD 26, then turned back into a code.
Searching and splitting strings
Two more operations are used constantly. Searching finds where one string appears inside another, such as finding the @ in an email address. Splitting breaks a string into a list of parts at a separator, so "Ada,17,82" split at commas gives "Ada", "17" and "82".
Together with substring, these let a program pull data out of text. The part before the @ is the user name, and the part after it is the domain. Validation of email addresses and postcodes is built from exactly these steps.
Check yourself. What is ASC("D") − ASC("A"), and what does the answer tell you?
Show the answer
ASC("D") is 68 and ASC("A") is 65, so the answer is 3. It gives the position of D in the alphabet counting from 0, which is the number a Caesar cipher works with.
Section 6
Validation and files
Validating input with a loop
Validation checks that input is sensible before a program uses it. Common checks are a range check, a presence check, a length check, a type check and a format check. Validation cannot prove that data is correct, only that it is reasonable.
The right construct for validation is a loop, not a single IF. The program must keep asking until the input passes, however many times the user gets it wrong. A REPEAT UNTIL loop fits naturally, because the input must be read at least once.
do
mark = int(input("Enter a mark from 0 to 100: "))
until mark >= 0 AND mark <= 100
Common mistake: validating with IF instead of a loop. An IF checks the input once. If the second attempt is also invalid, the program carries on with bad data. Only a loop guarantees that the value used has passed the check.
Validation and verification
Validation and verification are often confused. Validation checks that data is reasonable, for example that a date of birth is in the past. Verification checks that data was entered as intended, for example by asking for a new password twice and comparing the two entries.
Each kind of validation check catches a different problem. A range check stops a mark of 150. A presence check stops an empty name. A length check limits a password, a type check rejects letters in an age, and a format check tests a pattern such as a postcode.
Reading and writing files
Data in variables is lost when a program ends, so programs save it in files. A file must be opened, read or written, then closed. Reading usually happens in a loop that runs until the end of the file is reached.
myFile = openRead("scores.txt")
total = 0
while NOT myFile.endOfFile()
total = total + int(myFile.readLine())
endwhile
myFile.close()
A WHILE loop suits reading, because an empty file has no lines, so the body must be able to run zero times. Writing uses openWrite, writeLine and close. Opening a file for writing usually replaces its old contents, so programs that add to a file open it for appending instead.
A program that reads a file should also cope with problems, such as a missing file. Many languages use exception handling for this. In Python, the risky code goes in a try block, and an except block runs if an error occurs, so the program can report the problem instead of crashing.
Files usually hold text, one record per line. A comma-separated values file, or CSV file, separates the fields of each record with commas. Splitting each line at the commas gives the fields back, ready to be cast to the right types.
Writing a file mirrors reading it. The program opens the file for writing, writes each record with writeLine, then closes it. Closing matters, because many systems hold written data in a buffer and only save it to disk when the file is closed. A program that crashes before closing can lose data.
A text file can also be opened for appending, which adds new lines to the end and keeps what is already there. A log of every login, for example, is appended to, never overwritten. Choosing the wrong mode is a common way to lose a whole file of data in one run.
Choosing the right construct
Use a FOR loop when the number of passes is known before the loop starts, such as processing every item of an array. Use WHILE when the loop might not need to run at all, such as reading a file that may be empty. Use REPEAT UNTIL when the body must run at least once, such as asking for input.
Constructs in combination
Real programs nest these constructs inside each other freely. A validation loop sits inside a FOR loop that reads each pupil's mark. An IF inside that loop counts the passes. A file loop around the whole thing reads one class after another. Each construct is simple; the skill is in combining them so that the structure matches the problem.
When a program grows past a screenful, it becomes hard to follow, however well the constructs are chosen. The answer is to split it into named pieces, each doing one job, which is the subject of the next chapter.
Check yourself. Why does a REPEAT UNTIL loop suit validation better than a WHILE loop?
Show the answer
The input must be read before it can be checked, so the body must run at least once. A REPEAT UNTIL loop always runs its body before testing, while a WHILE loop would need the input read once before the loop as well.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| DIV | Whole-number quotient | 17 DIV 5 = 3 | Drops the remainder; // in Python |
| MOD | Remainder after division | 17 MOD 5 = 2 | n MOD 10 is the last digit; % in Python |
| IF … ELSEIF … ELSE | Runs the first branch whose condition is true | Grading a mark | Order the tests from the highest |
| CASE | Chooses a branch by a variable's value | Menu options | Clearer than a long ELSEIF chain |
| FOR loop | Count-controlled iteration | for i = 1 to 10 step 3 | Includes the end value; passes known in advance |
| WHILE loop | Pre-condition loop | while n > 0 | May run zero times |
| REPEAT UNTIL | Post-condition loop | Validation | Always runs at least once |
| substring | Characters from a start position | substring(3, 4) of COMPUTER = PUTE | Positions count from 0 |
| ASC and CHR | Character code and back | ASC("A") = 65 | Letters have consecutive codes |
| Trace table | The value of each variable after each step | Euclid's algorithm | One row per pass or change |
Programming task
Programming task: a Caesar cipher
Aim
Write a Python program that encrypts and decrypts messages with a Caesar cipher. Capital letters are shifted and wrap round from Z to A; every other character is left unchanged. Decrypting with the same key must give back the original message.
Design
A function shift(message, k) builds a new string one character at a time. For a capital letter, it works out the letter's position from 0 to 25, adds k, takes MOD 26 and turns the result back into a letter. Any other character is copied unchanged.
Decrypting is the same as shifting by −k, so one function does both jobs. Python's % operator always gives a result from 0 to 25 for a positive divisor, even when the sum is negative, so wrapping works in both directions.
Code
def shift(message, k):
result = ""
for character in message:
if "A" <= character <= "Z":
position = ord(character) - 65
new_position = (position + k) % 26
result = result + chr(new_position + 65)
else:
result = result + character
return result
def encrypt(message, k):
return shift(message, k)
def decrypt(message, k):
return shift(message, -k)
secret = encrypt("ZEBRA CROSSING", 3)
print(secret)
print(decrypt(secret, 3))
The loop is count-controlled, because it visits every character exactly once. The IF inside it is selection, and building the result step by step is sequence. All three constructs appear in a dozen lines.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | encrypt("ABC", 1) | BCD | A simple shift with no wrapping |
| 2 | encrypt("ZEBRA", 3) | CHEUD | Z must wrap round to C |
| 3 | decrypt("CHEUD", 3) | ZEBRA | Decryption reverses encryption |
| 4 | encrypt("HI THERE!", 5) | MN YMJWJ! | Spaces and punctuation stay unchanged |
| 5 | encrypt("ABC", 26) | ABC | A full turn of 26 returns the same letters |
| 6 | encrypt("", 4) | an empty string | An empty message gives an empty result |
| 7 | encrypt("XYZ", 29) | ABC | A key over 26 still wraps correctly |
Evaluation
The program meets its aim: every test passes, including wrapping in both directions and keys larger than 26. Tests 4 and 6 show that it handles characters it should not change, and an empty message, without errors.
The program only shifts capital letters, so lower-case input is left unchanged. An improvement would shift lower-case letters too, using 97 as the base. The cipher is also very weak, because only 25 keys need trying, which links to Compression, encryption and hashing.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. Name the three basic programming constructs and give an example of each.
Worked solution to Q1
Sequence runs steps one after another, such as reading two numbers then adding them. Selection chooses a path, such as an IF statement. Iteration repeats steps, such as a FOR loop over an array.
Q2. State the difference between a WHILE loop and a REPEAT UNTIL loop.
Worked solution to Q2
A WHILE loop tests its condition before each pass, so its body may run zero times. A REPEAT UNTIL loop tests after each pass, so its body always runs at least once, and it stops when the condition becomes true.
Q3. Give the difference between a variable and a constant, and one reason to use a constant.
Worked solution to Q3
A variable's value can change while the program runs, but a constant's value is fixed. A constant such as VAT_RATE makes the code easier to read, and its value only needs changing in one place.
Rung 2: Application
Q4. Calculate 1000 DIV 7 and 1000 MOD 7.
Worked solution to Q4
Seven goes into 1,000 142 times, because 7 × 142 = 994, and 7 × 143 = 1,001 is too big. So 1000 DIV 7 = 142. The remainder is 1000 − 994 = 6, so 1000 MOD 7 = 6.
Q5. Write down every value of i in for i = 2 to 15 step 4, and state how many passes the loop makes.
Worked solution to Q5
The values are 2, 6, 10 and 14. The next value would be 18, which is past 15, so the loop stops. It makes 4 passes, matching ⌊13 ÷ 4⌋ + 1 = 4.
Q6. Trace Euclid's algorithm for a = 84 and b = 36, and give the highest common factor.
Worked solution to Q6
84 MOD 36 = 12, so a becomes 36 and b becomes 12. Then 36 MOD 12 = 0, so a becomes 12 and b becomes 0. The loop stops, and the highest common factor is 12.
Q7. Find substring(2, 3) of "ALGORITHM", and explain how you counted.
Worked solution to Q7
Counting from 0, position 0 is A, 1 is L and 2 is G. Taking 3 characters from position 2 gives G, O and R, so the result is "GOR".
Rung 3: Analysis
Q8. An outer loop runs for i = 1 to 8, and an inner loop runs for j = 1 to i. How many times does the inner body run?
Worked solution to Q8
The inner loop runs once when i is 1, twice when i is 2, and so on up to 8 times. The total is 1 + 2 + … + 8 = 8 × 9 ÷ 2 = 36 passes.
Q9. A WHILE loop is written as while x != 10, with x starting at 1 and increased by 2 on each pass. Explain what happens.
Worked solution to Q9
x takes the values 1, 3, 5, 7, 9, 11 and so on, and is always odd. It never equals 10, so the condition never becomes false and the loop runs for ever. Using while x < 10 would fix it.
Q10. Trace the digit-sum loop from worked example 7 for n = 9046, and give the output.
Worked solution to Q10
Pass 1 adds 6, leaving 904. Pass 2 adds 4, making 10 and leaving 90. Pass 3 adds 0, leaving 9. Pass 4 adds 9, making 19 and leaving 0. The loop ends and prints 19.
Q11. Decide whether 2100 is a leap year, using the rule from worked example 4.
Worked solution to Q11
First, 2100 MOD 4 = 0 but 2100 MOD 100 = 0, so the first part of the condition is false. Next, 2100 MOD 400 = 100, so the second part is false too. So 2100 is not a leap year.
Rung 4: Stretch
Q12. Use the formula for the passes of a FOR loop on for i = 7 to 100 step 9. Give the number of passes and the last value of i.
Worked solution to Q12
Substituting into the formula, the passes are ⌊(100 − 7) ÷ 9⌋ + 1 = ⌊93 ÷ 9⌋ + 1 = 10 + 1 = 11. The last value is 7 + 10 × 9 = 97, because the next value, 106, would pass the end.
Q13. Explain why decrypting a Caesar cipher with key 3 is the same as encrypting with key 23.
Worked solution to Q13
Decrypting shifts each letter back 3 places. Shifting forward 23 places moves it 23 places on, and 3 + 23 = 26 is a full turn of the alphabet. So shifting forward 23 lands on the same letter as shifting back 3.
Q14. Write a condition that is true when a password is between 8 and 20 characters long and is not the same as the username.
Worked solution to Q14
The condition is password.length >= 8 AND password.length <= 20 AND password != username. All three parts must be true, so they are joined with AND. The length is tested twice to give a range check.
Exam practice
Exam technique and worked answer workshop
Trace tables earn marks row by row. Give each variable its own column, add a new row only when a value changes, and write the output in its own column. Keep going until the loop condition fails, and show the final test that ends the loop.
When asked to write code, use clear variable names and indent the body of every IF and loop. Examiners accept pseudocode or a real language, but the logic must be complete. Every loop needs a way to stop, and every IF chain needs its tests in the right order.
Learn exactly what DIV, MOD and substring do, because a single slip costs the mark. Check DIV and MOD by multiplying back, and check substring by counting positions from 0.
Exam question 1 (4 marks · Paper 02 · about 5 minutes)
(a) A film lasts 200 minutes. Calculate 200 DIV 60 and 200 MOD 60, and state what each result means. [2]
(b) State the values of 4725 MOD 10 and 4725 DIV 10. [2]
Mark scheme for exam question 1
- B1 200 DIV 60 = 3, the whole hours
- B1 200 MOD 60 = 20, the minutes left over
- B1 4725 MOD 10 = 5
- B1 4725 DIV 10 = 472
Exam question 2 (5 marks · Paper 02 · about 7 minutes)
The digit-sum algorithm from worked example 7 is run with n = 4725. Complete a trace table showing total and n after each pass, and state the output.
Mark scheme for exam question 2
- B1 pass 1: total 5, n 472
- B1 pass 2: total 7, n 47
- B1 pass 3: total 14, n 4
- B1 pass 4: total 18, n 0
- B1 output 18
Exam question 3 (5 marks · Paper 02 · about 6 minutes)
(a) State the values of i given by for i = 1 to 10 step 3. [2]
(b) An outer loop runs 4 times and an inner loop runs 6 times for each pass. State how many times the inner body runs. [1]
(c) An outer loop runs for i = 1 to 10 and an inner loop runs for j = 1 to i. Calculate how many times the inner body runs. [2]
Mark scheme for exam question 3
- B1 1, 4, 7
- B1 and 10, because the end value is included
- B1 24
- M1 1 + 2 + … + 10
- A1 55
Exam question 4 (5 marks · Paper 02 · about 7 minutes)
A function grade(mark) returns "A" for 70 or more, "B" for 60 to 69, "C" for 50 to 59 and "U" otherwise.
(a) Write the function using an IF … ELSEIF chain. [4]
(b) Explain why the order of the tests matters. [1]
Mark scheme for exam question 4
- B1 function header taking mark, and a return of the grade
- B1 tests mark >= 70 first, giving "A"
- B1 then mark >= 60 for "B" and mark >= 50 for "C"
- B1 else "U"
- B1 only the first true branch runs, so a lower test first would catch higher marks
Exam question 5 (6 marks · Paper 02 · about 9 minutes)
A school's attendance program must do three things. It must ask a teacher for a register code until a valid one is entered. It must read every line of a file that may be empty. It must print a report for each of the 30 pupils in a class. Discuss which type of loop should be used for each task.
Mark scheme for exam question 5
Level 3 (5–6 marks): a justified choice of loop for all three tasks. The answer explains whether the number of passes is known in advance and whether the body may need to run zero times. Code fragments or conditions support the choices. The answer is well organised and uses technical terms accurately.
Level 2 (3–4 marks): a correct choice for at least two tasks, with some justification. The explanation of why each loop fits is limited.
Level 1 (1–2 marks): some relevant points, such as naming a FOR loop for the class, with little justification. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- validating the register code needs a condition-controlled loop, because the number of attempts is not known
- REPEAT UNTIL suits it, because the code must be entered at least once before it can be checked
- the condition stops the loop only when a valid code has been entered
- reading the file needs a WHILE loop that runs while not at the end of the file
- WHILE tests first, so an empty file is handled with zero passes
- the report for 30 pupils has a known number of passes, so a FOR loop is used
- the loop variable can index the array of pupils, from 0 to 29
- each choice avoids unnecessary checks or the risk of an infinite loop
Annotated model answer: exam question 5
"The register code must be entered at least once, and the teacher may need several attempts. The number of passes is not known, so a condition-controlled loop is needed. REPEAT UNTIL suits it best, because its body runs before the test: do code = input() until code is valid." (Validation, justified, with the condition.)
"The file may be empty, so the loop must be able to run zero times. A WHILE loop tests first: while NOT file.endOfFile(), read a line. If the file is empty, the body is skipped." (File reading, justified.)
"There are exactly 30 pupils, so the number of passes is known before the loop starts. A FOR loop, for i = 0 to 29, prints each report, and i indexes the array of pupils." (Count-controlled loop, justified.)
"Choosing the loop that matches the task avoids extra checks, and it avoids the risk of a loop that never ends." (A concluding judgement.)
This answer reaches Level 3 and scores 6 marks. Each choice is tied to whether the passes are known and whether the body may run zero times.
Exam question 6 (6 marks · Paper 02 · about 9 minutes)
Write a function caesar(message, k) that returns the message with each capital letter shifted forward k places, wrapping Z round to A. Other characters must be unchanged.
Mark scheme for exam question 6
- B1 a loop over every character of the message
- B1 a check for a capital letter, between "A" and "Z"
- B1 the position found as ASC(character) − 65
- B1 characters that are not capitals added unchanged
- M1 the new position found as (position + k) MOD 26
- A1 converted back with CHR(new + 65), added to a result string that is returned
Annotated model answer: exam question 6
function caesar(message, k)
result = ""
for i = 0 to message.length - 1
c = message.substring(i, 1)
if c >= "A" AND c <= "Z" then
position = ASC(c) - 65
newPos = (position + k) MOD 26
result = result + CHR(newPos + 65)
else
result = result + c
endif
next i
return result
endfunction
The loop over every character earns the first mark, and the capital-letter test the second. The position calculation and the unchanged characters earn the next two. The MOD 26 wrap earns the method mark, and converting back and returning the result earns the final mark.
Exam question 7 (4 marks · Paper 01 · about 5 minutes)
(a) Give the values of ASC("A") and CHR(97). [2]
(b) State the result of "COMPUTER".substring(3, 4). [1]
(c) State the length of "COMPUTER". [1]
Mark scheme for exam question 7
- B1 ASC("A") = 65
- B1 CHR(97) = "a"
- B1 "PUTE"
- B1 8
Exam question 8 (5 marks · Paper 02 · about 7 minutes)
Euclid's algorithm repeats a, b = b, a MOD b while b is not 0.
(a) Trace the algorithm for a = 252 and b = 105, showing a, b and a MOD b on each pass. [3]
(b) State the result. [1]
(c) Explain why the loop must eventually stop. [1]
Mark scheme for exam question 8
- B1 pass 1: 252, 105, remainder 42
- B1 pass 2: 105, 42, remainder 21
- B1 pass 3: 42, 21, remainder 0
- B1 the result is 21
- B1 the remainder is always smaller than b, so b gets smaller on every pass and must reach 0
Connections
Synoptic link
These constructs are the raw material of every later programming chapter. Subroutines and recursion packages them into reusable functions and procedures, and shows a second way to repeat: a subroutine that calls itself. Algorithm analysis and Big O notation counts how many times loops run, which is exactly the nested-loop counting in section 3.
String handling relies on the character codes in Number systems and binary arithmetic. The Caesar cipher in the programming task is the simplest example of the encryption studied in Compression, encryption and hashing.
Synoptic question 1. A program checks every pair of 200 students with nested loops, where the inner loop runs from i + 1 to 199. How many pairs does it check?
Answer to synoptic question 1
For i = 0, the inner loop checks 199 pairs, then 198, and so on down to 0. The total is 199 + 198 + … + 1 = 199 × 200 ÷ 2 = 19,900 pairs. The count grows with the square of the class size.
Recap
Recap and next step
- Variables hold values that change and constants hold fixed values; DIV gives the whole-number quotient and MOD the remainder.
- Selection runs exactly one branch; an ELSEIF chain stops at its first true condition, so the order of the tests matters.
- A FOR loop includes its end value, and nested loops multiply their passes.
- WHILE tests first and may run zero times; REPEAT UNTIL tests last and always runs once. A trace table records every variable after each pass.
- Strings are numbered from 0; ASC and CHR convert between characters and codes, and MOD 26 wraps the alphabet.
- Validation needs a loop, not a single IF, and files are opened, read or written, and closed.
Next chapter: Subroutines and recursion packages these constructs into functions and procedures, passes data between them, and lets a subroutine call itself.
For your exam board
OCR A Level Computer Science (H446): this chapter covers the programming constructs of sequence, iteration and branching in section 2.2.1, Programming techniques, in Component 02, Algorithms and programming. Data types and character sets are in section 1.4.1, Data types, in Component 01.
AQA A Level Computer Science (7517): variables, constants, arithmetic operations including integer division and modulus, selection, iteration, string handling and file handling appear in the fundamentals of programming section, assessed on Paper 1 through the on-screen programming exam.