Programming Concepts · Cambridge syllabus 8.1 · Lesson 2 of 4
Data Types
Integers represent whole numbers; real values represent fractional numbers; characters represent one character; strings represent text; Booleans represent true or false. Choose types by the operations and meaning required, not only by appearance.
By the end, you can
- Understand integer data.
- Understand real/float data.
- Understand character data.
- Understand string data.
- Understand Boolean data.
- Select appropriate data types.
Basic data types
The data type of a variable says what kind of value it holds, how much memory that takes, and which operations are allowed on it. Choosing it is a real decision, and choosing badly produces bugs that are hard to see.
An integer is a whole number, positive or negative, with no fractional part: a count of pupils, a year, an index into an array. Integer arithmetic is exact, which is why counters and indexes are always integers.
A real, also called float, holds a number with a fractional part: a price, a temperature, an average. Reals are stored approximately, so two of them should not be tested for exact equality — 0.1 added to 0.2 does not give precisely 0.3 in binary, and a program that waits for a total to equal exactly 1.0 may wait for ever.
A character holds exactly one symbol, written in single quotes. A string holds a sequence of them, written in double quotes, and can be empty or hundreds of characters long. A string of digits is not a number: "25" cannot be added to 5 without conversion, which is the commonest type error there is, because input arrives as a string.
A Boolean holds only TRUE or FALSE and is what a condition evaluates to. It is the right type for anything with two states — IsValid, HasPaid, GameOver — and it makes conditions readable: WHILE NOT Finished says what it means.
Choose by asking what values are possible and what will be done with them. A telephone number is a string, not an integer, because it can start with a zero and is never arithmetic; money is a real or an integer number of pence; a yes-or-no answer is a Boolean.
Worth remembering
- Integer for whole numbers and counters; real for fractional values.
- Reals are approximate, so never test two of them for exact equality.
- A telephone number is a string: it can start with zero and is never used in arithmetic.
Worked example
A telephone number is usually text because arithmetic is inappropriate and leading zeros matter.
Practice
Warm-up · not marked
Check your understanding
Answer in your own words, then compare with the worked answer. Nothing here is saved or scored.
Worked answer
Integer, real and Boolean respectively.
Check your method, units and explanation against it.
Marked practice
Set 1 of 4 · easiest first · Checked as you go, with the worked answer. Sign in or create a free account to save your progress.