Skip to content

2.2.1 Programming fundamentals

GCSE · Paper 2 · Computational thinking, algorithms and programming · Section 2.2 · 20 flashcards · 12 practice questions

Questions

2.2.1 Programming fundamentals

Every program is built from a small set of ideas: storing values, doing calculations, making decisions and repeating steps. This topic covers all of them. All code is in the OCR Exam Reference Language, which is the style used in the exam.

Variables, constants and assignment

Definition
A variable is a named place in memory that stores a value. The value can change while the program runs.
Definition
A constant is a named value that is set once and cannot change while the program runs.
Assignment means giving a variable a value. It uses a single equals sign. The variable goes on the left and the value goes on the right.
pseudocode
score = 0
name = "Louise"
score = score + 10
const vat = 0.2

The line score = score + 10 works out the right-hand side first (0 + 10), then stores the answer back in score. The old value is replaced.

Use a constant for a value that never changes, such as a tax rate. If the value ever needs changing, you change it in one place only. It also makes the code easier to read, because vat is clearer than 0.2.

Key Point
Choose names that say what the variable holds. Use totalScore, not x. Good names make a program easier to read, test and fix.

Inputs and outputs

An input is data that goes into the program, for example from the keyboard. An output is data that comes out of the program, for example text on the screen.

pseudocode
myName = input("Please enter a name")
print("My name is " + myName)

The text inside input(...) is the prompt shown to the user. Whatever the user types is stored in the variable on the left. Input always arrives as a string, so numbers must be cast with int() or float() before you calculate with them. Casting is explained in 2.2.2.

pseudocode
age = int(input("Enter your age"))
print(age + 1)

The three programming constructs

Every program is made from three building blocks.

ConstructWhat it does
SequenceRuns the lines one after another, in order
SelectionChooses which lines to run, depending on a condition
IterationRepeats lines of code
Definition
Sequence means instructions run in the order they are written, from the first line to the last.
pseudocode
width = 4
height = 3
area = width * height
print(area)

Order matters. If the print line came first, area would not have a value yet.

Arithmetic operators

OperatorMeaningExampleResult
+Add6 + 410
-Subtract6 - 42
*Multiply6 * 424
/Divide (gives a real number)17 / 53.4
DIVWhole-number part of a division17 DIV 53
MODRemainder of a division17 MOD 52
^To the power of (exponent)2 ^ 38
Key Point
17 divided by 5 is 3 remainder 2. So 17 / 5 gives 3.4, 17 DIV 5 gives 3 (the whole number of times 5 fits in 17) and 17 MOD 5 gives 2 (what is left over).

Order of operations

Brackets are worked out first. Then ^. Then *, /, DIV and MOD. Then + and -.

Worked Example
Task: Work out each answer.

- 2 + 3 * 4: multiply first, so 3 * 4 = 12, then 2 + 12 = 14.
- (2 + 3) * 4: the brackets come first, so 5 * 4 = 20.
- 2 ^ 3 + 1: the power comes first, so 8 + 1 = 9.
- 7 ^ 2 is 7 * 7 = 49.

Uses of DIV and MOD

Worked Example
Task: A film is 125 minutes long. Show the length in hours and minutes.
pseudocode
length = 125
hours = length DIV 60
minutes = length MOD 60
print(hours)      // 2
print(minutes)    // 5

125 divided by 60 is 2 remainder 5, so the film is 2 hours 5 minutes.

MOD is also used to test for even numbers. A number is even when dividing by 2 leaves no remainder.

pseudocode
if number MOD 2 == 0 then
    print("Even")
endif

For example 14 MOD 2 is 0, so 14 is even. 15 MOD 2 is 1, so 15 is odd.

Using a constant in a calculation

pseudocode
const vat = 0.2
price = 50
total = price + price * vat
print(total)      // 60

Multiplication happens before addition, so price * vat is 10, and 50 + 10 is 60.

Comparison operators

A comparison gives the answer True or False. These are used in conditions.

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 5False
<Less than3 < 5True
<=Less than or equal to5 <= 5True
>Greater than3 > 5False
>=Greater than or equal to5 >= 6False
Warning
One equals sign (=) is assignment: it stores a value. Two equals signs (==) is a comparison: it asks whether two values are equal. In a condition, use ==.

Boolean operators

A condition can be built from smaller conditions using AND, OR and NOT.

OperatorMeaning
ANDTrue only when both conditions are True
ORTrue when at least one condition is True
NOTTurns True into False and False into True

Suppose score is 70 and lives is 0.

ConditionWorkingResult
score > 50 AND lives > 0True AND FalseFalse
score > 50 OR lives > 0True OR FalseTrue
NOT (lives > 0)NOT FalseTrue

AND is often used to check a range. The test age >= 13 AND age <= 17 is True only for ages from 13 to 17.

Exam Tip
Work out each small comparison first, write True or False beside it, then apply AND, OR or NOT. Use brackets to make the order clear.

Selection

Definition
Selection means the program chooses which code to run, depending on whether a condition is True or False.

if, elseif and else

pseudocode
mark = int(input("Enter mark"))
if mark >= 80 then
    print("Distinction")
elseif mark >= 60 then
    print("Merit")
else
    print("Pass")
endif

The program checks the conditions from the top. The first one that is True is run, then the program skips to endif. The else part runs only if none of the conditions were True.

markCheck 1 (mark >= 80)Check 2 (mark >= 60)Output
80Truenot checkedDistinction
65FalseTrueMerit
59FalseFalsePass

Notice that 80 gives Distinction because >= includes the value 80 itself.

switch

A switch statement chooses between many fixed values of one variable. It is a tidy alternative to a long chain of elseif lines.

pseudocode
switch day :
    case "Sat":
        print("Saturday")
    case "Sun":
        print("Sunday")
    default:
        print("Weekday")
endswitch

If day holds "Sun", the program prints Sunday. If day holds "Tue", no case matches, so the default part runs and it prints Weekday.

Iteration

Definition
Iteration means repeating a block of code. It is also called a loop.

There are two kinds. A count-controlled loop repeats a set number of times. A condition-controlled loop repeats until a condition changes.

Count-controlled: for loops

pseudocode
total = 0
for i = 1 to 4
    total = total + i
next i
print(total)      // 10

The loop variable i takes each value from 1 to 4, including both ends. Here is a trace table.

itotal after the pass
11
23
36
410
Key Point
for i = 0 to 9 runs 10 times, with i taking the values 0, 1, 2 ... 9. The last value is included. To count how many times a loop runs, work out (last - first + 1).

Use step to count in jumps, including backwards.

pseudocode
for i = 2 to 10 step 2
    print(i)          // 2, 4, 6, 8, 10
next i

for i = 10 to 0 step -3
    print(i)          // 10, 7, 4, 1
next i

In the second loop the next value would be -2, which is past 0, so the loop stops after 1.

Condition-controlled: while loops

A while loop checks its condition before each pass. If the condition is False at the start, the loop never runs.

pseudocode
n = 1
while n < 50
    n = n * 3
endwhile
print(n)          // 81
n at the start of the passn < 50?n after the pass
1True3
3True9
9True27
27True81
81Falseloop stops

Condition-controlled: do-until loops

A do-until loop checks its condition after each pass, and it stops when the condition is True. So it always runs at least once.

pseudocode
do
    guess = int(input("Guess the number"))
until guess == 7
Pros & Cons
while loopdo-until loop
Condition checked at the startCondition checked at the end
Repeats while the condition is TrueRepeats until the condition is True
May run zero timesAlways runs at least once
Warning
If nothing inside a while loop ever makes its condition False, the loop never ends. This is an infinite loop. Always check that the loop changes the variable used in the condition.

Putting it together

Worked Example
Task: Ask for a password until the user types "tiger". Count the attempts and print the count.
pseudocode
attempts = 1
password = input("Enter password")
while password != "tiger"
    password = input("Enter password")
    attempts = attempts + 1
endwhile
print(attempts)

If the user types "cat", "dog" then "tiger", attempts goes 1, 2, 3 and the program prints 3. The first input is outside the loop so the condition has a value to check.

Other topics you may use in programs, such as string handling, arrays, files and sub programs, are covered in 2.2.3.

Exam technique

  • •
    State or give: write the value or the answer only, such as the number printed.
  • •
    Complete: fill the gaps in the code with the correct keywords, such as while, endwhile or elseif.
  • •
    Trace: work through the code line by line, writing down each variable's value. A trace table helps. Check carefully whether a loop includes its last value.
  • •
    Correct or identify the error: say the line number, then what is wrong, then what it should be.
  • •
    Write: use the reference language, or a high-level language you have learned. Do not use plain English. Give variables a value before using them, use == in conditions, and finish every if with endif, every while with endwhile and every for with next.
  • •
    Explain: give a point and a reason, for example "a constant is used so the value only has to be changed in one place".