Programming Concepts

Computer Science revision notes · Cambridge (CIE) · 0984

1. Variables, constants and data types

Every program manipulates data: numbers, text, true/false values. To work with data, the program stores values in named (which can change) and (which cannot).

Variables

A variable is a named storage location whose value can change while the program is running.

In CIE pseudocode, a variable is declared with DECLARE and a data type:

DECLARE Age : INTEGER
DECLARE Price : REAL
DECLARE Name : STRING
DECLARE FirstInitial : CHAR
DECLARE GameOver : BOOLEAN

After declaration, a value is assigned with the arrow operator ←:

Age ← 17
Price ← 9.99
Name ← "Alice"
FirstInitial ← 'A'
GameOver ← FALSE

Common exam question

Declaring a variable in pseudocode

Question: Write the pseudocode statement that declares a named variable of a given data type, sometimes followed by statements that store a value in it (1–2 marks, or one mark point of several).

Asked in 4 of the 17 papers. The declaration is DECLARE <identifier> : <data type>, with the colon and the type keyword in capitals, as in DECLARE Message : STRING; asked alone, it is worth one mark. In the two questions where it is one step of a text-file task, declaring the string variable is one of the mark points, so write it first even when the wording seems to assume the variable already exists.

When you also store a value, assign it with ← and match the quotes to the type: double quotes for a STRING (Title ← "Go") and single quotes for a CHAR (Grade ← 'A'). One scheme pays two marks for two declarations and their two assignments, one for every two correct lines.

Constants

A constant is a named storage location whose value is set once and cannot change for the rest of the program.

CONSTANT Pi ← 3.142
CONSTANT Vat ← 0.20
CONSTANT MaxLives ← 3

Constants are named in the same PascalCase style as variables, and they make programs easier to maintain: if the VAT rate changes, only one line of the program has to be edited.

Common exam question

What variables and constants are for

Question: Explain how a program should use variables and constants, complete a sentence that defines a constant, or circle the words that name places where data can be stored (1–3 marks).

Asked in 3 of the 17 papers. A variable holds a value that can change while the program runs; a constant holds a value that is set once and never changes during execution. Both store data, as does an array: those are the three words to circle, not input, output, procedure or dimension.

The explain version pays one mark per point up to three: both store data; constants are for values that must never change, such as a tax rate; variables hold values the program calculates or changes as it runs; and both should have meaningful identifiers so that other programmers understand their purpose. The tick-box distractors describe a variable, an array (values of one data type) and a store for mixed data types, so read every option first.

Naming conventions

Identifiers (the names of variables and constants) should:

  • Use letters and digits only, no spaces.
  • Start with a capital letter, not a digit.
  • Be in PascalCase: each word capitalised, e.g. TotalScore.
  • Be descriptive: StudentScore is far better than s or x.
  • Never contain an underscore, an accented letter or any other symbol — and this applies to constant names too.

Common exam question

Suggesting meaningful identifiers for an algorithm

Question: Suggest meaningful identifiers for an algorithm's array and three variables that have single-letter names (3 marks).

Asked in 3 of the 17 papers, always as a later part of a longer pseudocode question. One mark is for the array's name, two for all three variable names and one for two of them (two of the three schemes give it for just one). Choose from what the algorithm does with each name: a variable a FOR or WHILE loop steps through, or one that goes up by one each time, is Index or Counter, a running sum is Total, a value parked during a swap is Temp, the number of items is Length, a mean is Average, and the array takes the name of what it holds, such as Names or Values.

Names are judged on meaning, so even a plain MyArray was credited for an array. Write them with a capital first letter and no spaces.

Common exam question

Making a program easier to understand and maintain

Question: State features a programmer can use so that another programmer can understand and maintain a program, sometimes with an example of each (2–6 marks).

Asked in 2 of the 17 papers. The credited features are meaningful identifiers, comments that explain what the code does, procedures and functions for the separate tasks, and white space such as blank lines and indentation. When an example is asked for, it earns a mark of its own, so make it concrete: a name like RunningTotal, a comment line such as // reset the counters for the next customer, or a procedure call such as CALL PrintReceipt(Total).

When the question follows one on identifiers and asks for other ways, leave identifiers out and give two of the remaining three.

Data types

There are five basic data types. Choosing the right one for each variable makes the program more accurate and uses memory efficiently.

Data typeUsed forPseudocode keywordExamples
IntegerWhole numbers (no fractional part)INTEGER10, -5, 0, 1000
RealNumbers with a fractional partREAL3.14, -2.5, 0.0
CharA single characterCHAR'a', 'B', '7', '£'
StringA sequence of charactersSTRING"Hello world", "ABC", ""
BooleanA logical valueBOOLEANTRUE, FALSE

Notes on the difference between and string:

  • A CHAR is exactly one character, written in single quotes ('A').
  • A STRING is zero or more characters, written in double quotes ("Apple").

Casting

Sometimes a value needs to be converted from one type to another. This is called . For example, in a language such as Python a number typed by the user arrives as a string and may need to be converted to an integer before arithmetic can be done on it.

Common slip: in Python, adding "5" to "3" as strings gives "53" (concatenation), not 8. Cast to integer first.

Picking the right data type

A short reference for matching everyday data to the most suitable CIE type:

Kind of valueBest typeQuick test
Whole-number counts (age, score, year)INTEGERNo decimal point ever needed
Measurements and money (1.75 m, £8.50)REALA fractional part is possible
Names, addresses, sentencesSTRINGMore than one character, or any text
A single flag character ('M', 'F', 'Y', 'N')CHARExactly one character
Yes/no, on/off, paid/unpaidBOOLEANTwo possible values: TRUE or FALSE

When two types look possible, prefer the smaller one. A house number is an INTEGER, not a STRING. A pH reading is a REAL, not a STRING. Storing numbers as strings means losing the ability to compare or do arithmetic on them later.

Common exam question

Identifying and defining the basic data types

Question: Link four descriptions of data to the best-fitting data type from a list of five, or define the integer and real data types and give an example of each (4 marks).

Asked in 2 of the 17 papers, one mark per line or per point. The credited matches follow the definitions: a whole number is INTEGER, a number with a fractional part is REAL, a single letter is CHAR, and a word or phrase is STRING. BOOLEAN, which holds only TRUE or FALSE, is the type left unused when every description is a number or some text.

When you define integer and real, the example is a separate mark from the statement, so write an actual value: 42 for an integer and 3.75 for a real. The question asks for the most appropriate type, so a single letter goes to CHAR rather than STRING, and anything with decimal places goes to REAL, never INTEGER.

2. Arithmetic operators

CIE pseudocode supports the standard arithmetic operators, plus two functions specific to integer division.

OperationPseudocodePython
Addition++
Subtraction--
Multiplication**
Division//
Exponentiation (raised to power)^**
Integer division (quotient)DIV(a, b)//
Modulus (remainder)MOD(a, b)%

CIE pseudocode uses these operators: +, -, *, / and the exponentiation operator ^, plus the two integer-division operations DIV and MOD, which are written as function calls: DIV(a, b) and MOD(a, b). The ^ operator raises a number to a power (for example 2 ^ 3 = 8, and X ^ 3 for "X cubed").

Common exam question

Recognising counting, totalling and average statements

Question: Link each pseudocode statement to its use (counting, totalling, finding an average, a conditional statement or calling a procedure), or give the line numbers of the statements in an algorithm that do the totalling and form the loops (3–4 marks).

Asked in 2 of the 17 papers, one mark per line or per answer. Counting adds one to the same variable each time: Count ← Count + 1. Totalling adds a value other than 1 to a running total: Total ← Total + Value. Finding an average divides a sum by the number of values: Mean ← (A + B + C) / 3. An IF line is the conditional statement and a CALL line uses a procedure. In the matching version one use is left over, so do not force every label onto a statement. In the line-number version, FOR … NEXT is the count-controlled loop and REPEAT … UNTIL the post-condition loop.

DIV: integer division

DIV(a, b) returns the whole-number part of a divided by b, throwing away any remainder.

DIV(17, 5) returns 3      // 17 ÷ 5 = 3 remainder 2
DIV(20, 4) returns 5      // 20 ÷ 4 = 5 exactly
DIV(9, 2) returns 4       // 9 ÷ 2 = 4 remainder 1

Useful for splitting things into equal groups: "how many full minutes are in 130 seconds?" → DIV(130, 60) returns 2.

MOD: remainder

MOD(a, b) returns the remainder after a is divided by b.

MOD(17, 5) returns 2      // 17 ÷ 5 = 3 remainder 2
MOD(20, 4) returns 0      // 20 ÷ 4 = 5 remainder 0
MOD(9, 2) returns 1       // 9 ÷ 2 = 4 remainder 1

Useful for a classic check: "is a number divisible by 2?" → MOD(Number, 2) = 0 is true for even numbers.

Worked example

Using DIV and MOD together to split a total

A checkout system stores a total price in whole pence. Convert 503 pence into pounds and pence.

Solution:

  • Whole pounds = DIV(503, 100) = 5 (integer quotient: how many complete hundreds fit)
  • Remaining pence = MOD(503, 100) = 3 (the remainder after removing those complete hundreds)
  • Result: £5.03

The same pattern applies any time a total must be split into a larger unit and a leftover: DIV(TotalItems, GroupSize) gives the number of complete groups; MOD(TotalItems, GroupSize) gives what is left over.

ROUND: rounding to a number of decimal places

ROUND(value, places) returns value rounded to places decimal places.

ROUND(3.14159, 2) returns 3.14   // two decimal places
ROUND(8.6, 0) returns 9          // zero decimal places: nearest whole number

value should be a real number and places a whole number. ROUND is useful for tidying up money or measurements before they are output.

RANDOM(): a random number

RANDOM() returns a random real number between 0 and 1 inclusive. It takes no arguments.

To get a random whole number in a range, scale the result and round it. For example, a random whole number from 0 to 6 is ROUND(RANDOM() * 6, 0). RANDOM() is the standard way to add chance to a program, such as rolling a dice or shuffling.

3. Comparison (relational) operators

Comparison operators compare two values and return a (TRUE or FALSE). They are the building blocks of IF statements and loop conditions.

OperatorMeaningExampleResult
=Equal toAge = 18TRUE if age is 18
<>Not equal toScore <> 0TRUE if score is not zero
<Less thanSpeed < 30TRUE if speed under 30
>Greater thanTemperature > 25TRUE if temperature over 25
<=Less than or equal toMark <= 40TRUE if mark is 40 or below
>=Greater than or equal toAge >= 18TRUE if age is at least 18

Common slip: in some real programming languages (Python, Java), the test for equality is ==, not =. In CIE pseudocode the single = is correct, so use it in pseudocode answers.

Common exam question

Identifying operators and their types

Question: Tick the operator that means less than or equal to, or draw lines from operators such as >=, AND, DIV and + to the operator types arithmetic, logical and Boolean (1–4 marks).

Asked in 2 of the 17 papers, one mark per correct tick or line. Know the symbols: <= is less than or equal to, >= greater than or equal to and <> not equal to; the wrong options offered were OR, < and >=.

Sort operators by what they do, because the group names have changed. +, -, *, /, ^, DIV and MOD calculate a number: arithmetic. =, <, <=, >, >= and <> compare two values: relational in the current syllabus, labelled "logical" on earlier papers. AND, OR and NOT combine TRUE and FALSE values: logical now, labelled "Boolean" on earlier papers. So with the labels Boolean, arithmetic and logical on offer, >= goes to logical, AND to Boolean, and DIV and + to arithmetic.

4. Logical (Boolean) operators

Logical operators combine Boolean values and return a Boolean. The three you must know are AND, OR and NOT.

OperatorMeaningResult
ANDResult is TRUE only when every combined condition is also TRUE(Age >= 13) AND (Age <= 18) is true only for ages in that range
ORTrue if at least one condition is true(Score > 90) OR (BonusActive = TRUE) is true if either holds
NOTFlips the result of one condition (true becomes false, and the other way around)NOT GameOver is true while the game is still going

Truth tables

The three operators are fully defined by their truth tables (these come up again in topics 26 and 27 on Boolean logic).

AND

ABA AND B
FALSEFALSEFALSE
FALSETRUEFALSE
TRUEFALSEFALSE
TRUETRUETRUE

OR

ABA OR B
FALSEFALSEFALSE
FALSETRUETRUE
TRUEFALSETRUE
TRUETRUETRUE

NOT

ANOT A
FALSETRUE
TRUEFALSE

Combining comparisons and logical operators

A single comparison only tests one thing. To check more than one fact at once, link comparisons with AND, OR or NOT. Each part on either side of the operator must be its own complete comparison.

AND requires both sides to be true. A common pattern is a range check built from two comparisons:

IF (Mark >= 0) AND (Mark <= 100)
   THEN
      OUTPUT "Valid mark"
ENDIF

OR requires at least one side to be true. Useful when several different values should be treated the same way:

IF (Day = "Saturday") OR (Day = "Sunday")
   THEN
      OUTPUT "Weekend"
ENDIF

NOT flips the result of a single comparison, so it is true when the underlying condition is false:

IF NOT (Account = "locked")
   THEN
      OUTPUT "Login allowed"
ENDIF

Always bracket each comparison. The brackets are not strictly required by precedence, but they make the intent obvious and stop slips like writing Mark >= 0 AND <= 100, which is not valid pseudocode.

Operator precedence

When multiple operators appear in one expression:

  1. Brackets first.
  2. Then arithmetic (*, / before +, -); DIV(a, b) and MOD(a, b) are function calls, so they are worked out first.
  3. Then comparisons (<, >, =, <>, <=, >=).
  4. Then NOT.
  5. Then AND.
  6. Then OR.

When in doubt, use brackets generously. (A AND B) OR C is much clearer than relying on the reader to remember precedence.

5. String operations

A string is a sequence of characters such as "Hello world" or "PASSWORD123". CIE pseudocode names four string operations you must know.

LENGTH

LENGTH(s) returns the number of characters in the string s.

Password ← "letmein"
OUTPUT LENGTH(Password)      // outputs 7

Name ← ""
OUTPUT LENGTH(Name)          // outputs 0 (empty string)

A common use is validation: rejecting a password that is too short.

INPUT Password
IF LENGTH(Password) < 8
   THEN
      OUTPUT "Password must be at least 8 characters"
ENDIF

SUBSTRING

SUBSTRING(s, start, length) returns a piece of the string s, beginning at position start and length characters long.

In CIE pseudocode, strings are 1-indexed: the first character is at position 1.

Word ← "Revision"
OUTPUT SUBSTRING(Word, 1, 3)   // outputs "Rev"
OUTPUT SUBSTRING(Word, 4, 5)   // outputs "ision"
OUTPUT SUBSTRING(Word, 1, 1)   // outputs "R"

Useful for extracting parts of formatted data: e.g. taking the first three letters of a postcode, or splitting a date string "05/12/2024" into day, month and year.

UCASE (uppercase)

UCASE(s) returns the string s with every letter changed to uppercase.

Name ← "Sarah"
OUTPUT UCASE(Name)             // outputs "SARAH"

LCASE (lowercase)

LCASE(s) returns the string s with every letter changed to lowercase.

Name ← "SARAH"
OUTPUT LCASE(Name)             // outputs "sarah"

Putting them together

A common idiom: standardise an input before comparing it so that minor differences in case do not cause false rejections.

Common exam question

Writing pseudocode with the string functions

Question: Write pseudocode statements that store a string, extract part of it with SUBSTRING, output it in upper or lower case and output its length (4–6 marks, one per mark point).

Asked in 4 of the 17 papers, twice alongside reading or writing a text file. Each function used correctly is usually a mark point: UCASE(Text) or LCASE(Text) for the case change, LENGTH(Text) for the character count, and SUBSTRING(Text, Start, Number) with the string first, then the start position, then the number of characters. In one scheme SUBSTRING carried three marks: the right string, start and length. Position 1 is the first character and spaces count, so number the characters first. The outputs share one mark at most.

They also appear in algorithms to trace or interpret: LENGTH(Entry) < 8 is a minimum-length rule, LCASE(Entry) = Entry is true only when nothing is in upper case, and SUBSTRING(Entry, Index, 1) in a loop tests one character at a time.

Worked example

Extracting a word and changing its case

Write pseudocode statements that store the string "Practice Makes Perfect" in the variable Phrase, extract and output the word "Makes", output the whole phrase in upper case, and output the number of characters in it.

Solution:

Number the characters from 1, counting the spaces: "Practice" fills positions 1 to 8, the space is position 9, so "Makes" starts at position 10 and is 5 characters long.

DECLARE Phrase : STRING
Phrase ← "Practice Makes Perfect"
OUTPUT SUBSTRING(Phrase, 10, 5)
OUTPUT UCASE(Phrase)
OUTPUT LENGTH(Phrase)
  • SUBSTRING(Phrase, 10, 5) outputs Makes
  • UCASE(Phrase) outputs PRACTICE MAKES PERFECT
  • LENGTH(Phrase) outputs 22: 8 + 1 + 5 + 1 + 7 characters, the two spaces included

A start of 9 would return " Make" and a start of 11 would return "akes ", so check the count before you commit to it.

6. A reference card

A short reminder of the keywords, operators and string functions on one page.

Pseudocode keywords for variables and constants

DECLARE <identifier> : <data type>
CONSTANT <identifier> ← <value>

Data types

INTEGERREALCHARSTRINGBOOLEAN

Arithmetic

+-*/^DIV(a, b)MOD(a, b)

Comparison

=<><><=>=

Logical (Boolean)

ANDORNOT

String functions

LENGTH(s)SUBSTRING(s, start, length)UCASE(s)LCASE(s)

Common pseudocode pitfalls

  • Single = for equality in CIE pseudocode (not ==).
  • Single quotes for CHAR, double quotes for STRING.
  • ← is the only operator; = means equality (comparison), so never use it to assign a value.
  • are 1-indexed in CIE pseudocode (not 0-indexed like Python).
  • Always declare a before using it, with the right data type.
  • Use MOD(a, b) for "is divisible by" rather than dividing and checking the fractional part.