10.2 Arrays: Paper 2: Fundamental Problem-Solving and Programming Skills 10 Data Types and Structures
10.2 Arrays: Paper 2: Fundamental Problem-Solving and Programming Skills 10 Data Types and Structures
Definition
An array is a data structure that can hold a set of data items under a single identifier name. The
data items (also known as elements) are of identical data type and are accessed by consecutive
index numbers.
Difference between variable and array: A variable can only hold one data value while an array
can hold multiple values.
Example
    •   If a user wishes to store the surnames of 25 students using variables, they would have to
        declare 25 variables.
    •   Using an array, they could store all 25 values in a single array set up to accept 25 data items.
Declaring an array
Declaring an array is a similar process to declaring a variable; the same naming and data type
requirements exist.
The difference is that we need to define the size of the array which will be determined by the
number of data items that the array is required to hold.
Example
If we want to store the highest scores that a player achieves in a game, we can do this in an array.
Let's say the array will store 10 values for high scores.
Size of array
Note:
Specific data items can be placed in the array at the time of declaration (i.e. initialising the
array).
// initialising
Highscores[0] ← 83
Highscores[1] ← 75
Highscores[2] ← 77
Highscores[3] ← 82
Highscores[4] ← 95
Highscores[5] ← 99
Highscores[6] ← 84
Highscores[7] ← 70
Highscores[8] ← 91
Highscores[9] ← 80
Note 2:
The statement below is a short way of declaring and initialising the array but it is not in accordance
to the standard way of writing pseudocode for array as per the syllabus. However you will come
across it in examples of pseudocode in hand-outs as a way of saving time when writing pseudocode.
Highscores ← [83, 75, 77, 82, 95, 99, 84, 70, 91, 80]
Dim Highscores() As Integer = {83, 75, 77, 82, 95, 99, 84, 70, 91, 80}
Dim Highscores = New Integer() {83, 75, 77, 82, 95, 99, 84, 70, 91, 80}
                                       Highscores
                       Index       1        83
                                   2        75
                                   3        77
                                   4        82
                                   5        95
                                   6        99
                                   7        84
                                   8        70
                                   9        91
                                  10        80
Highscores
                       Index       0        83
                                   1        75
                                   2        77
                                   3        82
                                   4        95
                                   5        99
                                   6        84
                                   7        70
                                   8        91
                                   9        80
Fixed-length arrays are used when we know in advance how many elements we need to work with;
variable-length (dynamic) arrays are used when we do not know in advance how many elements we
will be working with.
In that case, the array is declared with a maximum size as per the question set.
Once we have created an array, we can then write data to the array or read data from it.
The following pseudocode outputs data items from the array Highscores created in the above
example.
        OUTPUT Highscores[3]
        OUTPUT Highscores[8]
        OUTPUT Highscores[0]
        Console.WriteLine(Highscores(3))
        Console.WriteLine(Highscores(8))
        Console.WriteLine(Highscores(0))
The output would be the fourth, ninth and first elements i.e. 82, 91 and 83.
We can also use a variable to read data from or write data to an array.
We can do this by replacing the index with the variable name.
Reading data from the Highscores array using a variable as index in pseudocode:
Reading data from the Highscores array using a variable as index in Visual Basic:
If the variable Count held the value 3, this would output the data from the fourth element in the
array i.e. 82.
To read multiple values from an array, we can use a FOR … TO … NEXT loop.
Reading from the Highscores array using FOR loop in Visual Basic:
Note:
    •   The Count variable used refers to the index that is currently being read.
    •   It begins at 0 and when it gets to the next Count, it will increase by 1 till it gets to 3.
    •   Therefore this loop would read and output elements at index numbers 0, 1, 2 and 3.
    •   With the Highscores array, this loop would output the values 83, 75, 77 and 82.
Reading from the Highscores array not starting at index 0 in Visual Basic:
This loop would output the values 77, 82, 95, 99, 84 and 70.
We can ask a program to write elements to an array, i.e. inputting elements in an array. To write, we
need to create / declare an array without initialising and we use a loop structure to do the input.
Note:
    •   The values that are entered in the Highscores array go in this order 83, 75, 77, 82, 95, 99,
        84, 70, 91, 80.
    •   The FOR … TO … NEXT loop would write the value input to the relevant index.
    •   It would start with writing the first input to index 0 which is the value 83 and keep repeating
        till it had written to index 9 which is the value 80.
Using the for loop structure to assign the elements individually (initialising empty array)
Pseudocode:
        FOR Count ← 0 TO 9
                Highscores[Count] ← “”
        NEXT Count
Visual Basic:
        For Count = 0 To 9
                Highscores(Count) = “”
        Next
Updating array
To do this, we state the data location in the array that we want to write data to, followed by the data.
The following pseudocode writes the score of 90 in the second element location of the array
Highscores:
Highscores[1] ← 90
Writing the score of 90 in the second element location of the array Highscores in Visual Basic:
Highscores(1) = 90
If the array already held a value at this particular index, that value would be overwritten with the
new value. This would mean that the current value in location or index 1 of the array Highscores
would be overwritten with the value 90.
The Highscores array would now look like this when it is output:
Highscores ← [83, 90, 77, 82, 95, 99, 84, 70, 91, 80]
Updated value
Updating data in the Highscores array using a variable as index in Visual Basic:
If the variable Count still held the value 3, this would overwrite the data in the fourth element in the
array i.e. 82 with the value 75.
The Highscores array would now look like this when it is output:
        Highscores ← [83, 75, 77, 75, 95, 99, 84, 70, 91, 80]
                                                          Updated value
Linear search
Linear search is used to find whether a given item or element is present in an array and if it is
present, then at what location it occurs. It is also known as sequential search. We keep on
comparing each element with the element to search until it is found or the list ends.
Example
Consider an array of car makes. User inputs a car make and system outputs whether the entered car
make is found or not.
REPEAT
        IF Car[Count] = Carmake THEN
                Found ← TRUE
                OUTPUT “Car make found at position “, Count
        ELSE
                Count ← Count + 1
        ENDIF
UNTIL (Found = TRUE) OR (Count = 9)
Visual Basic program to search linearly through array of car makes using repeat until loop:
Dim Car() As String = {"Renault", "Ford", "Hyundai", "Vauxhall", "Audi", "BMW", "Toyota",
                          "Citroen", "Jaguar"}
Dim Carmake As String
Dim Count As Integer = 0
Dim Found As Boolean = False
Do
         If Car(Count) = Carmake Then
                  Found = True
                  Console.WriteLine("Car make found at position " & Count)
         Else
                  Count = Count + 1
         End If
Loop Until (Found = True) Or (Count = 9)
Visual Basic program to search linearly through array of car makes using while loop:
Dim Car() As String = {"Renault", "Ford", "Hyundai", "Vauxhall", "Audi", "BMW", "Toyota",
                          "Citroen", "Jaguar"}
Dim Carmake As String
Dim Count As Integer = 0
Dim Found As Boolean = False
Bubble Sort
Example
First Pass
(-5 72 0 33 -9) → (-5 72 0 33 -9), algorithm compares first two elements, here no swap (-5 < 72)
(-5 72 0 33 -9) → (-5 0 72 33 -9), swap since 72 > 0
(-5 0 72 33 -9) → (-5 0 33 72 -9), swap since 72 > 33
(-5 0 33 72 -9) → (-5 0 33 -9 72), swap since 72 > -9
Second Pass
(-5 0 33 -9 72) → (-5 0 33 9 72), no swap between first two elements (because -5 < 0)
(-5 0 33 -9 72) → (-5 0 33 -9 72), no swap (because 0 < 33)
(-5 0 33 -9 72) → (-5 0 -9 33 72), swap since 33 > -9
(-5 0 -9 33 72) → (-5 0 -9 33 72), no swap (because 33 < 72)
Third Pass
(-5 0 -9 33 72) → (-5 0 -9 33 72), no swap between first two elements (because -5 < 0)
(-5 0 -9 33 72) → (-5 -9 0 33 72), swap since 0 > -9
(-5 -9 0 33 72) → (-5 -9 0 33 72), no swap (because 0 < 33)
(-5 -9 0 33 72) → (-5 -9 0 33 72), no swap (because 33 < 72)
Fourth Pass
Pseudocode to bubble sort array [-5, 72, 0, 33, -9] using repeat until loop:
FOR Index ← 0 TO 4
        OUTPUT Number[Index]                    // outputs -9, -5, 0, 33, 72
NEXT Index
Visual Basic program to bubble sort array [-5, 72, 0, 33, -9] using repeat until loop:
Sub Main()
        Dim Number() As Integer = {-5, 72, 0, 33, -9}
        Dim Index, Temp As Integer
        Dim ArraySize As Integer = 4
        Dim Swapped As Boolean
        For Index = 0 To 4
                 Console.WriteLine(Number(Index))              ' outputs -9, -5, 0, 33, 72
        Next
End Sub
Another way to bubble sort is to use nested for loops. The pseudocode and VB program are on
Pages 18 – 19.
Pseudocode to bubble sort array [-5, 72, 0, 33, -9] using nested FOR loops:
FOR Count ← 0 TO 4
        OUTPUT Number[Count]                    // outputs -9, -5, 0, 33, 72
NEXT Count
Visual Basic program to bubble sort array [-5, 72, 0, 33, -9] using nested FOR loops:
Sub Main()
        Dim Number() As Integer = {-5, 72, 0, 33, -9}
        Dim Count, i, j, Temp As Integer
        Dim ArraySize As Integer = 4
        Dim Swapped As Boolean = False
                ' If no number was swapped that means array is sorted now, break the loop.
                If (Not Swapped) Then
                         Exit Sub
                End If
        Next
        For Count = 0 To 4
                Console.WriteLine(Number(Count))                ' outputs -9, -5, 0, 33, 72
        Next
End Sub
So far, we have discussed how to use a one dimensional (1D) array to hold a list of items. Each
element of a 1D array is accessed by a single index value, for example Highscores[2].
But we can also have a two dimensional array (also known as a matrix) or we can have multi-
dimensional arrays. Where one-dimensional arrays are lists, two dimensional arrays are tables.
Example
                                                     Board
        First element in
                                                Index for columns
        2D array
                                                0       1       2
                   Index for rows      0        15      97      18
                                       1        45      56      19
                                       2        89      62      22
                                       3        11      10      44
                                       4        20      90      65
                                                                            Rows
                                       5        33      26      17
                                       6        40      81      74
                                       7        78      39      93
                                       8        36      24      38
                                       9        10      51      83
The array Board is a 2D array with 10 rows and 3 columns which contains 30 elements.
The first element 15 is located at position [0, 0].
The last element 83 is located at position [9, 2].
The element 90 is located at position [4, 1].
The element 89 is located at position [2, 0].
So elements are identified using row number followed by column number.
     Name of 2D         Lower bound Upper bound   Lower bound Upper bound    Data type of
     array              of row      of row        of column   of column      2D array
Populate the 2D array Board using loop (input data values in the array)
Pseudocode to populate 2D array Board with the numbers as they are on Page 20:
FOR RowCounter ← 0 TO 9
        FOR ColumnCounter ← 0 TO 2
                OUTPUT “Enter the numbers row wise i.e. input 15 and
                            press enter, then input 97 and press enter, etc: ”
                INPUT Board[RowCounter, ColumnCounter]
        NEXT ColumnCounter
NEXT RowCounter
Visual Basic to populate the 2D array Board with the numbers as they are on Page 20:
For RowCounter = 0 To 9
        For ColumnCounter = 0 To 2
                Console.WriteLine("Enter the numbers row wise i.e. input 15 and press enter, then
                                       input 97 and press enter, etc : ")
                Board(RowCounter, ColumnCounter) = Console.ReadLine()
        Next
Next
Dim Board = New Integer(9,2) {{15, 97, 18}, {45, 56, 19}, {89, 62, 22}, {11, 10, 44},
{20, 90, 65}, {33, 26, 17}, {40, 81, 74}, {78, 39, 93}, {36, 24, 38}, {10, 51, 83}}
    •   They store many data values under one name. This means we do not have to use or
        remember many variable names.
    •   We can easily find an item of data by specifying its index.
    •   We can easily read or write many values by using a FOR … TO … NEXT loop.
    •   Memory can be wasted if we do not use all the array's index numbers to hold data.
    •   Arrays can only hold data of one data type (the type specified when the array is defined).
Question 1
Write a pseudocode that iterates through an array of integers and outputs the average. Declare and
initialise the array with the following set of integers: 12, 14, 10, 6, 7, 11 and 3. Write the equivalent
program code in Visual Basic (VB).
Pseudocode:
FOR Count ← 0 TO 6
        Sum ← Sum + Number[Count]
NEXT Count
Average ← Sum/Count
OUTPUT “The average is ” , Average
Visual Basic:
For Count = 0 To 6
        Sum = Sum + Number(Count)
Next
Average = Sum/Count
Console.WriteLine(“The average is ” & Average)
Examples
Consider Question 1. A procedure or function is passed the 1D array, calculates the average of the
elements in the array and returns the average value.
// Main program
        Number ← [12, 14, 10, 6, 7, 11, 3]
        DECLARE Ave : REAL
        CALL Calcaverage(Number, Ave)
        OUTPUT “The average is ” , Ave
// End of main program
Sub Main()
        Dim Number() As Integer = {12, 14, 10, 6, 7, 11, 3}
        Dim Ave As Decimal
        Call Calcaverage(Number, Ave)
        Console.WriteLine(“The average is ” & Ave)
End Sub
// Main program
        Number ← [12, 14, 10, 6, 7, 11, 3]
        OUTPUT “The average is ” , Calcaverage(Number)
// End of main program
Sub Main()
        Dim Number() As Integer = {12, 14, 10, 6, 7, 11, 3}
        Console.WriteLine(“The average is ” & Calcaverage(Number))
End Sub
Question 2
Use either pseudocode or programming statements in Visual Basic to write an algorithm / program
to record the height in metres and the shoe size of each teenager in a group of 30. These values are
to be stored in arrays.
Pseudocode:
FOR Count ← 1 TO 30
        OUTPUT “Enter height: ”
        INPUT Height[Count]
Visual Basic:
Note: For the purpose of testing, the array size has been set to 4.
For count = 1 To 4
        Console.WriteLine("Enter height: ")
        Height(Count) = Console.ReadLine()
Question 3
Input and store the names and marks for 30 students who have sat three computer science tests.
You must store the names in a one-dimensional array and the marks and total score for each
student in one-dimensional arrays. All the marks must be validated on entry and any invalid
marks rejected. You may assume that the students' names are unique.
Your program must include appropriate prompts for the entry of data.
Error messages and other output need to be set out clearly and understandably.
All variables, constants and other identifiers must have meaningful names.
The program must be fully tested.
Visual Basic:
Note: For the purpose of testing, the array size has been set to 2.
For Count = 0 To 2
        Do
                Console.WriteLine("Enter marks for test1:")
                Test1(Count) = Console.ReadLine()
        Do
                Console.WriteLine("Enter marks for test2:")
                Test2(Count) = Console.ReadLine()
        Do
                Console.WriteLine("Enter marks for test3:")
                Test3(Count) = Console.ReadLine()
Console.WriteLine("Total score of student " & Names(Count) & " is " & Total(Count))
Next
Classavg = Classtotal/Count
Question 4
Write pseudocode and program code to input the following values in a 2D array as shown below
and output the average, largest and smallest values.
Pseudocode:
Average ← Total/20
Visual Basic:
For RowCounter = 1 To 5
        For ColumnCounter = 1 To 4
                Console.WriteLine("Enter the numbers column wise i.e. input 1.3 and press enter,
                                         then input 6.2 and press enter, etc : ")
                NumberArray(RowCounter, ColumnCounter) = Console.ReadLine()
Average = Total/20
Examples
Consider Question 4. A procedure or function is passed the 2D array, calculates the average of the
elements in the array and returns the average value. Here, we assume start index is zero.
// Main program
        DECLARE Number : ARRAY[0:4, 0:3] OF REAL
        Number[0,0] ← 1.3
        Number[0,1] ← 7.5
        Number[0,2] ← -3.2
        Number[0,3] ← 4.8
        Number[1,0] ← 6.2
        Number[1,1] ← -10.5
        Number[1,2] ← 14.7
        Number[1,3] ← 18.3
        Number[2,0] ← -11.5
        Number[2,1] ← -20.2
        Number[2,2] ← 6.8
        Number[2,3] ← 9.7
        Number[3,0] ← 15.6
        Number[3,1] ← 5.9
        Number[3,2] ← 16
        Number[3,3] ← 7
        Number[4,0] ← -19.2
        Number[4,1] ← 13.3
        Number[4,2] ← 2.5
        Number[4,3] ← 4.4
Sub Main()
        Dim Number(4, 3) As Integer
        Number(0,0) = 1.3
        Number(0,1) = 7.5
        Number(0,2) = -3.2
        Number(0,3) = 4.8
        Number(1,0) = 6.2
        Number(1,1) = -10.5
        Number(1,2) = 14.7
        Number(1,3) = 18.3
        Number(2,0) = -11.5
        Number(2,1) = -20.2
        Number(2,2) = 6.8
        Number(2,3) = 9.7
        Number(3,0) = 15.6
        Number(3,1) = 5.9
        Number(3,2) = 16
        Number(3,3) = 7
        Number(4,0) = -19.2
        Number(4,1) = 13.3
        Number(4,2) = 2.5
        Number(4,3) = 4.4
        Dim Ave As Decimal
        Call Calcaverage(Number, Ave)
        Console.WriteLine(“The average is ” & Ave)
End Sub
// Main program
        DECLARE Number : ARRAY[0:4, 0:3] OF REAL
        Number[0,0] ← 1.3
        Number[0,1] ← 7.5
        Number[0,2] ← -3.2
        Number[0,3] ← 4.8
        Number[1,0] ← 6.2
        Number[1,1] ← -10.5
        Number[1,2] ← 14.7
        Number[1,3] ← 18.3
        Number[2,0] ← -11.5
        Number[2,1] ← -20.2
        Number[2,2] ← 6.8
        Number[2,3] ← 9.7
        Number[3,0] ← 15.6
        Number[3,1] ← 5.9
        Number[3,2] ← 16
        Number[3,3] ← 7
        Number[4,0] ← -19.2
        Number[4,1] ← 13.3
        Number[4,2] ← 2.5
        Number[4,3] ← 4.4
Sub Main()
        Dim Number(4,3) As Integer
        Number(0,0) = 1.3
        Number(0,1) = 7.5
        Number(0,2) = -3.2
        Number(0,3) = 4.8
        Number(1,0) = 6.2
        Number(1,1) = -10.5
        Number(1,2) = 14.7
        Number(1,3) = 18.3
        Number(2,0) = -11.5
        Number(2,1) = -20.2
        Number(2,2) = 6.8
        Number(2,3) = 9.7
        Number(3,0) = 15.6
        Number(3,1) = 5.9
        Number(3,2) = 16
        Number(3,3) = 7
        Number(4,0) = -19.2
        Number(4,1) = 13.3
        Number(4,2) = 2.5
        Number(4,3) = 4.4
It is highly recommended to read the whole chapter on Arrays in the Cambridge International
AS & A Level Computer Science Textbook (by Helen Williams & David Watson).
References
PIPER, T. (2016) Cambridge International AS and A Level Computer Science Revision Guide.
United Kingdom: Cambridge University Press.
(2019) Teach-ICT A level Computer Science OCR H446 Data Structures [WWW] Teach-ICT.com.
Available from: http://www.teach-
ict.com/2016/A_Level_Computing/OCR_H446/1_4_data_types_structures_algorithms/142_data_st
ructures/arrays/miniweb/index.php [Accessed 20/01/19]
(2019) What is Bubble Sort? - Definition from Techopedia [WWW] Techopedia.com. Available
from: https://www.techopedia.com/definition/3757/bubble-sort [Accessed 20/01/19]
(2019) Data Structures and Algorithms Bubble Sort [WWW] tutorialspoint.com. Available from:
https://www.tutorialspoint.com/data_structures_algorithms/bubble_sort_algorithm.htm [Accessed
20/01/19]
(2019) The Bubble Sort and Sort Dance Activities [WWW] Teaching London Computing. Available
from: https://teachinglondoncomputing.org/the-bubblesort-activity/ [Accessed 20/01/19]