Tutorial 8
🔢
Arrays
9618 A-Level
So far we have just looked at how to store single values in variables or constants - if we need to store multiple values of the same data type, we can use arrays
Some advantages of arrays:
- Can easily loop over them - for assigning, inputting, calculating the min/max/mean/total, searching, sorting, filtering etc
- Less tedious and more flexible than having to create 100s of variables for our data
1
Declaration & Assignment - 1D Arrays
The general syntax for declaring an array is as follows:
DECLARE <identifier> : ARRAY[<dimensions>] OF <data type>
Note: "dimensions" should be integer pairs in the form <lower bound>:<upper bound>
Below we declare and assign to a 1D array of strings, with 5 elements - a 1D array is a simple list of elements
Declaration & Assignment - 2D Arrays
While sometimes a 1D array is appropriate, sometimes we might want a 2D array which can be though of as a combination of rows and columns - much like a spreadsheet
For example, assume we want to store both the person's first and last name in separate, easily accessible locations - in our spreadsheet analogy, we can create a 2D array with 5 rows to store our 5 people and 2 columns to store the first & last name respectively
The other example can be used to declare a 3x3 grid for a simple board game like noughts and crosses - in this example, let's use a loop to automatically assign a space character to represent an available cell in the board grid
Note: the order you access elements is row, column, which is the opposite to e.g. x, y co-ordinates in maths - the acronym I remember being told at school to remember this was roman catholic to remember the "rc" order - an alternate acronym could be remote control
2
Outputting Arrays - 1D
In pseudocode, you can't simply use OUTPUT arr to output the contents of an array - Cambridge want you to learn how output actually works - i.e. by looping through each element
Note: for IGCSE/O-Level, they will usually tell you the length of the array is either stored in some variable/constant - e.g. NumberOfPeople or you can infer it from the question - e.g. "hourly temperatures are taken daily" which indicates you need a 7x24 or 24x7 2D array. One question - presumably by mistake - they didn't give any way of determining the length of the array - in that case, you can just make up some variable/constant and pretend that stores the length in the 15 marker
Outputting Arrays - 2D
In this case, since we only have 2 columns, we can access them directly - if we had a large number of columns, we could use a nested loop, looping through the rows in the outer loop, then the columns in the inner loop
3
Min, Max, Sum, Mean
Many IGCSE/O-Level 15 markers and some A-Level questions require us to calculate the minimum, maximum, sum and mean of all numbers in an array
Looking at the code below, note:
- We assign min & max as being the first element - this is since, e.g. if giving min a huge default value, then if all values happened to be larger than this, we would think the min was this default value we initially assigned it - same for max, if we chose a small/negative initial value, but the real values all happened to be less than it
- We then loop through all elements in the array
- Min: if the current element is smaller than the current minimum, then set this current element as the new minimum
- Max: if the current element is bigger than the current maximum, then set this current element as the new maximum
- Sum: add each element to the sum
- Mean: divide the sum by the number of elements
- Note: in this example, we could have also assigned sum to be the first element, then started our loop from element 2
4
Linear Search
Often we want to search to see whether a specific value exists in an array - we can use linear search to do that:
- Initialise an index variable to point to first element in array
- Loop through array element-by-element
- If current element if is the value we are searching for, then update flag/return TRUE if in a function etc
- If item hasn't been found after looping through all elements in the array, then we know the item doesn't exist
Note: we can also write this as a function, returning TRUE if we find the item, while returning FALSE is we have looped through the entire array and not found the item
5
Bubble Sort
In order to sort an array in either ascending or descending order, we can use bubble sort:
- Assume array is unsorted and loop to the n-1 position (e.g. 1 to 4, if 5 elements) in the array on the first iteration
- Compare elements pair by pair - if in the wrong order (i.e. if current element bigger than next element for ascending order...or current element smaller than next for descending order), then swap them by making use of a temporary variable
- If elements are not sorted after looping over all pairs, then go back to the start
More detailed comments can be seen in the code
Note: when we swap, we need the temporary variable - this is since if we do a <-- b, both variables now have the same value at this point - b <-- a will be redundant - hence why we need to move one value into a temporary variable before we update it, then assign this temporary variable value to the other variable. Drawing a picture with arrows representing the assignments between 3 variables can help with understanding.
6
Test Scores
Create a program to ask the user to enter the names (can't be empty) and test scores (validated between 0-100) of 5 students - then:
- Count the number of students who passed (scored 50% or more)
- Display the students in descending order of grades
- Display the min, max, sum and total of all the marks
- Ask the user to enter a specific student's name, then output their score, or an error message if they don't exist
7
Golf Tournament
A golf tournament consists of 4 days - each day, the player will have a score (total number of shots) - your program should
- Ask the player to enter the scores for each of the 4 days - the score should be at least 18, symbolising the technically possible, but realistically impossible feat of achieving 18 holes in one
- Output the lowest, highest, average daily scores, as well as their overall total score for the 4 day competition