Cambridge AS & A Level9608

Data representation in programming

Computer Science 9608 Chapter Notes

What this chapter covers

Data representation in programming
ShareWhatsAppPost
Data representation in programming notes

Unable to load PDF

The notes viewer could not load. Please refresh the page.

Read online free. Download a watermarked copy with a free account.

Read the notes

The full Data representation in programming notes as text: skim, search, and jump between subtopics.

~14 min read

1. Core Data Types in Programming

A data type is a classification that tells the computer how to interpret a value. It defines what kind of data a variable can hold (e.g., whole numbers, text, true/false values) and what operations can be performed on that data. Choosing the correct data type is crucial for writing efficient and error-free programs. The most common fundamental types are Integer, Real, Character, String, and Boolean.

Key term

Data Type: A classification of data which tells the system how the programmer intends to use the data, determining the values it can hold and the operations that can be performed on it.

Examiner insight

Examiners look for justification when you select a data type. It is not enough to just name the type; you should briefly explain why it is the most suitable choice for the given data.

Common pitfall

Confusing Integer and Real types. For example, using an Integer to store a value like a price (£19.99) or an average score would either cause an error or lose the decimal part.

Worked example 15 marks

A program needs to store details for a library book. For each piece of information below, choose the most appropriate data type from Integer, Real, String, Char, or Boolean. Justify your choice for each.

  • Title
  • Number of pages
  • Price
  • Is it currently on loan?
  • Shelf location code (e.g., 'F')
  1. 1
    1. Title: String. A book title consists of a sequence of characters, letters, and possibly numbers, which is the definition of a string.
  2. 2
    1. Number of pages: Integer. The number of pages will always be a whole number.
  3. 3
    1. Price: Real. Price can include decimal values (e.g., 9.99), so a Real (or float) is required to store the fractional part.
  4. 4
    1. Is it currently on loan?: Boolean. This is a simple yes/no or true/false question, which is exactly what the Boolean data type is for.
  5. 5
    1. Shelf location code: Char. Since the example 'F' is a single character, the Char data type is the most memory-efficient choice.

Recap

  • An Integer stores whole numbers (e.g., -5, 0, 100).
  • A Real (or Float) stores numbers with decimal points (e.g., 3.14, -0.05).
  • A Char stores a single character (e.g., 'A', '7', '$').
  • A String stores a sequence of characters (e.g., "Hello World").
  • A Boolean stores one of two values: True or False.
  • Choosing the right data type prevents errors and saves memory.

Quick check

  1. What data type would you use to store a person's age in years?1 mark
  2. Which data type is most suitable for storing the average mark in a test, which was 72.5?1 mark

2. Representing Characters: ASCII and Unicode

Computers do not understand letters or symbols; they only work with binary numbers. To represent text, we use character sets, which are standardized tables that map each character to a unique binary code. The two most important character sets are ASCII and Unicode.

ASCII (American Standard Code for Information Interchange) traditionally uses 7 bits, allowing it to represent 128 different characters. This is enough for all uppercase and lowercase English letters, numbers 0-9, and common punctuation. Extended ASCII uses 8 bits (1 byte) to represent 256 characters.

Unicode was created to overcome the limitations of ASCII. It aims to include every character from every language in the world. Unicode characters can be represented using different encodings, such as UTF-8 and UTF-16. A single Unicode character can take up 1 to 4 bytes, allowing for over a million possible characters.

Key term

Character Set: A defined list of characters recognized by the computer, where each character is represented by a unique numeric code.

Common pitfall

Assuming that all characters, including emojis and accented letters like 'é', can be represented by standard ASCII. They cannot, and require a system like Unicode.

Fun fact

The '😂' (Face with Tears of Joy) emoji has a Unicode value of U+1F602. Storing this single 'character' requires more space than three standard ASCII characters combined.

Worked example 12 marks

The ASCII code for the character 'A' is 65 (denary). What is the denary ASCII code for the character 'D'?

  1. 1
    1. The letters of the alphabet are stored in sequential order in the ASCII table.
  2. 2
    1. 'B' will be 66, 'C' will be 67, and 'D' will be 68.
  3. 3
    1. Therefore, the denary ASCII code for 'D' is 68.

Worked example 23 marks

A software company is developing a new social media application to be used globally. Explain why they should use Unicode instead of ASCII for storing user posts.

  1. 1
    1. ASCII is limited to 128 or 256 characters and primarily supports English and some Western European languages.
  2. 2
    1. A global application will have users who type in many different languages, such as Mandarin, Arabic, Russian, and Japanese, which have unique characters not found in ASCII.
  3. 3
    1. Unicode is a universal character set designed to represent characters from all modern and historic languages.
  4. 4
    1. By using Unicode, the application can correctly store, process, and display text from any user in any language, ensuring a functional and inclusive user experience worldwide.

Recap

  • Computers use character sets to represent text with binary codes.
  • ASCII uses 7 or 8 bits and is suitable for English text.
  • Unicode uses more bits (e.g., 8, 16, 32) and can represent characters from all world languages.
  • Using Unicode is essential for software intended for international use.
  • A string is stored as a sequence of these binary character codes.

Quick check

  1. How many bits are used in the standard ASCII character set?1 mark
  2. State the main advantage of Unicode over ASCII.1 mark

3. Using Variables and Constants

In programming, we use named storage locations to hold data. A 'variable' is a named location in memory whose value can be changed as the program runs. Think of it as a labeled box where you can store something, and later replace it with something else. A 'constant' is a named location whose value is set once and cannot be changed during program execution. Constants are useful for values that should never change, like the value of Pi or the maximum number of attempts in a game.

Before you can use a variable, you must 'declare' it, which means giving it a name and a data type. 'Assignment' is the process of putting a value into a variable or constant, typically using an assignment operator like `=` or `<-`.

DECLARE <VariableName> : <DataType>

<VariableName> <- <Value>

CONSTANT <ConstantName> = <Value>

Key term

Variable: A named location in memory used to store a value that can be changed during program execution.

Examiner insight

Candidates often lose marks for not declaring variables before use in pseudocode questions. Always include a declaration section at the start of your algorithm.

Fun fact

The first programmer to be credited with using the term 'variable' in a programming context was Christopher Strachey in the early 1950s, a pioneer of early British computing.

Worked example 13 marks

Analyse the following pseudocode and determine the final value of the 'Score' variable.

DECLARE Score : INTEGER DECLARE Bonus : INTEGER

Score <- 50 Bonus <- 20 Score <- Score + Bonus Score <- Score - 5

  1. 1
    1. `Score <- 50`: The variable Score is assigned the value 50.
  2. 2
    1. `Bonus <- 20`: The variable Bonus is assigned the value 20.
  3. 3
    1. `Score <- Score + Bonus`: The current value of Score (50) is added to the value of Bonus (20). The result, 70, is assigned back to Score. Score is now 70.
  4. 4
    1. `Score <- Score - 5`: 5 is subtracted from the current value of Score (70). The result, 65, is assigned back to Score.
  5. 5
    1. The final value of Score is 65.

Recap

  • A variable is a named memory location for data that can change.
  • A constant is a named memory location for data that does not change.
  • Variables must be declared with a name and a data type before use.
  • The assignment operator (`<-` or `=`) is used to store a value in a variable.
  • Using constants for fixed values (like tax rates) makes code easier to read and maintain.

Quick check

  1. What is the key difference between a variable and a constant?1 mark
  2. What is the term for giving a variable a name and a data type?1 mark

4. Manipulating String Data

A string is a sequence of characters, and it is one of the most common data types you will work with. Programming languages provide a rich set of built-in functions to manipulate strings. Common operations include:

  • Concatenation: Joining two or more strings end-to-end to form a new string. The `+` operator is often used for this.
  • Length: Finding the number of characters in a string.
  • Substring: Extracting a portion of a string. This is often done with functions like LEFT, RIGHT, or MID (or slicing).
  • Conversion: Changing a string of digits into a number (e.g., "123" to 123) or a number into a string (e.g., 45 to "45") to perform the correct operations.

LENGTH(MyString)

MyString.SUBSTRING(start, num_chars)

STRING_TO_INT(MyString)

INT_TO_STRING(MyNumber)

Key term

Concatenation: The process of joining two or more strings together to create a new, single string.

Common pitfall

Attempting to perform mathematical calculations on numbers that are stored as strings. For example, if `VarA` is "5" and `VarB` is "10", `VarA + VarB` will result in the string "510", not the number 15.

Worked example 15 marks

A program stores a user's full name in the format 'Firstname Lastname' in a variable called `FullName`. `FullName` currently holds the value "David Jones". Write the pseudocode steps to create a username that consists of the first letter of the first name and the full last name, all in lowercase. For "David Jones", the result should be "djones".

  1. 1
    1. Declare variables: `DECLARE FullName, FirstName, LastName, Username : STRING`, `DECLARE FirstInitial : CHAR`
  2. 2
    1. Assign the initial value: `FullName <- "David Jones"`
  3. 3
    1. Extract the first initial: `FirstInitial <- FullName.SUBSTRING(0, 1)` (assuming 0-based indexing)
  4. 4
    1. Find the position of the space: `SpacePosition <- FullName.FIND(" ")`
  5. 5
    1. Extract the last name: `LastName <- FullName.SUBSTRING(SpacePosition + 1, LENGTH(FullName) - SpacePosition - 1)`
  6. 6
    1. Concatenate the parts to form the username: `Username <- FirstInitial + LastName`
  7. 7
    1. Convert the username to lowercase: `Username <- Username.LOWER()`
  8. 8
    1. The final value in `Username` is "djones".

Recap

  • A string is a sequence of characters.
  • Concatenation joins strings together.
  • Functions like LENGTH and SUBSTRING allow you to inspect and extract parts of a string.
  • You must convert strings to numbers before doing arithmetic.
  • String indexing is often 0-based, meaning the first character is at position 0.

Quick check

  1. What is the length of the string "IGCSE CS"?1 mark
  2. What is the result of concatenating the strings "File" and "Name"?1 mark

5. Storing Data in 1D Arrays

An array is a data structure used to store a collection of elements, all of the same data type, in a contiguous block of memory. A one-dimensional (1D) array can be visualized as a single row or column of numbered slots, where each slot holds one element. To access a specific element in the array, you use its 'index' or 'subscript' – a number that indicates its position. Indexing often starts at 0 in many languages (0-based indexing) or at 1 (1-based indexing). Arrays are static, meaning their size is fixed when they are created.

DECLARE <ArrayName> : ARRAY[<LowerBound>:<UpperBound>] OF <DataType>

Accessing an element: <ArrayName>[<index>]

Key term

Array: A data structure that stores a fixed-size, sequential collection of elements of the same data type, accessible by an index.

Examiner insight

Examiners frequently test array manipulation within loops. You must be comfortable writing pseudocode to iterate through an array to find a value (linear search), calculate a total or average, or find the highest or lowest value.

Common pitfall

The 'off-by-one' error. This happens when a loop or index access is incorrect by one position, often by using `<` instead of `<=` in a loop condition, or trying to access an element at an index that is outside the array's valid range (e.g., accessing `MyArray[5]` in an array of size 5 that is indexed 0 to 4).

Worked example 16 marks

An array called `TestScores` is used to store the scores of 5 students. The array is 0-indexed. The scores are 88, 92, 75, 100, and 84.(a) Write a pseudocode statement to declare this array.(b) What is the value of `TestScores[2]`?(c) Write a pseudocode loop to calculate and output the total of all scores in the array.

  1. 1

    (a) `DECLARE TestScores : ARRAY[0:4] OF INTEGER`

  2. 2

    (b) Since the array is 0-indexed, the first element is `TestScores[0]`, the second is `TestScores[1]`, and the third is `TestScores[2]`. The value of `TestScores[2]` is 75.

  3. 3

    (c) `DECLARE Total : INTEGER` `DECLARE Index : INTEGER` `Total <- 0` `FOR Index <- 0 TO 4` ` Total <- Total + TestScores[Index]` `NEXT Index` `OUTPUT Total`

Recap

  • An array stores multiple values of the same data type under a single name.
  • Each element in an array is accessed using a unique index.
  • Array indexing can be 0-based (0 to size-1) or 1-based (1 to size).
  • Arrays are ideal for storing lists of related data, like student names or daily temperatures.
  • Loops are commonly used to process all elements in an array sequentially.

Quick check

  1. If an array is declared as `MyData[0:9]`, how many elements can it store?1 mark
  2. All elements in an array must have the same what?1 mark

6. Making Data Persistent with Files

When your program ends, all the data stored in its variables and arrays (which are held in RAM) is lost. This is because RAM is 'volatile' storage. To save data permanently, we must write it to a 'file' on a secondary storage device like a hard drive or SSD. This is called 'persistent storage'.

The basic process for using a file involves three steps:

  1. Open: You open a file and specify a mode. The main modes are READ (to get data from the file), WRITE (to put data into the file, overwriting existing content), and APPEND (to add new data to the end of the file).
  2. Process: You either read data from the file into your program's variables or write data from your variables into the file.
  3. Close: You must close the file. This ensures all data is correctly saved and makes the file available to other programs.

OPENFILE <filename> FOR READ/WRITE/APPEND

READFILE <filename>, <variable>

WRITEFILE <filename>, <data>

CLOSEFILE <filename>

Key term

Persistent Storage: The characteristic of computer storage that allows it to retain data even when the device is not powered, such as a hard disk or solid-state drive.

Examiner insight

Questions on file handling often involve combining arrays and loops. A typical task is to read data from a file line-by-line and store it in an array, or to process data in an array and write the results to a file.

Common pitfall

Forgetting to close a file after writing to it. Operating systems often buffer file writes, and the final data may not be physically written to the disk until the file is closed. This can lead to empty or incomplete files.

Worked example 14 marks

A program has a 1D array called `Usernames` containing three names: "amy", "ben", and "carl". Write pseudocode to save these three usernames to a text file called `users.txt`, with each username on a new line.

  1. 1
    1. Declare the array and a loop counter: `DECLARE Usernames : ARRAY[0:2] OF STRING`, `Usernames <- ["amy", "ben", "carl"]`, `DECLARE Index : INTEGER`
  2. 2
    1. Open the file in WRITE mode. This will create the file if it doesn't exist or overwrite it if it does: `OPENFILE "users.txt" FOR WRITE`
  3. 3
    1. Loop through the array from the first to the last element: `FOR Index <- 0 TO 2`
  4. 4
    1. Inside the loop, write the current username from the array to the file: `WRITEFILE "users.txt", Usernames[Index]`
  5. 5
    1. Continue the loop: `NEXT Index`
  6. 6
    1. After the loop has finished, close the file to save the changes: `CLOSEFILE "users.txt"`

Recap

  • Files are used for persistent data storage because RAM is volatile.
  • The three main file operations are Open, Process (Read/Write), and Close.
  • Opening a file in WRITE mode erases its previous contents.
  • Opening a file in APPEND mode adds new data to the end of the file.
  • It is crucial to close a file to ensure data is saved correctly.

Quick check

  1. What is the difference between opening a file in WRITE mode and APPEND mode?2 marks
  2. Why is it important to close a file after you have finished using it?1 mark

End-of-chapter exercise

Test yourself on the whole chapter. Work through these before moving on.

  1. For a school's student database, identify the most appropriate data type for the following fields: StudentID (e.g., 18432), DateOfBirth, and HasPaidFees. Justify one of your choices.4 marks
  2. Explain two differences between the ASCII and Unicode character sets.4 marks
  3. A 1D array called `Temperatures` stores the 7 daily average temperatures for a week. The array is 1-indexed. Write a pseudocode algorithm that iterates through the array and counts how many days the temperature was above 20.0 degrees.5 marks
  4. What is the final value of the string variable `Result` after the following pseudocode is executed? DECLARE S1, S2, Result : STRING S1 <- "Computer" S2 <- "Science" Result <- S1.SUBSTRING(0,3) + S2.LENGTH()3 marks
  5. Describe the difference between a variable and a constant, and give a suitable example of where a constant would be used in a program.3 marks
  6. Explain why files are necessary for a computer program that needs to store user preferences.2 marks
  7. A text file named `data.txt` contains a list of numbers, one per line. Write a pseudocode algorithm to read each number from the file and output only the numbers that are greater than 100.6 marks
  8. A program uses the statement `Score <- "25" + "50"`. Explain why this will not produce the numerical result 75, and state what the result will be.3 marks
  9. An array `Names` is declared as `ARRAY[0:99]` of String. What is an 'off-by-one' error in the context of this array? Provide a line of pseudocode that would cause this error.3 marks
  10. A company is creating a login system. The username must be the first letter of the user's first name followed by their last name, up to a maximum of 7 characters. Given `FirstName = "Robert"` and `LastName = "Williamson"`, write the steps to produce the username "rwillia".5 marks

Go deeper

Practise and revise with member-only material for this chapter.

Free notes are just the start.

Unlock every Workbook and Chapter at a Glance, and generate your own worksheets and predicted papers.

Explore plans

Related chapters