0% found this document useful (0 votes)
7 views42 pages

10.2 Arrays: Paper 2: Fundamental Problem-Solving and Programming Skills 10 Data Types and Structures

Notes

Uploaded by

ihoh90x
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views42 pages

10.2 Arrays: Paper 2: Fundamental Problem-Solving and Programming Skills 10 Data Types and Structures

Notes

Uploaded by

ihoh90x
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Cambridge A & AS Level Computer Science 9618 Arrays

Paper 2: Fundamental Problem-Solving And Programming Skills


10 Data Types And Structures
10.2 Arrays

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.

Each individual value held within an array is identified by an index number.


Index numbers are sequential and in Visual Basic the numbering starts from zero.

Prepared by K.Ramkissoon, St Joseph's College 1


Cambridge A & AS Level Computer Science 9618 Arrays

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.

Declaring this array in pseudocode:

DECLARE Highscores : ARRAY[0:9] OF INTEGER

Lower bound Upper bound Data type of


Name of array of array of array array

Size of array

Note:

• The index starts with 0.


• The array that we are working with is a one-dimensional array (1D array), i.e. a linear
array or single-dimension array.
• If the index starts with 1:
DECLARE Highscores : ARRAY[1:10] OF INTEGER
• When writing pseudocode, either method of numbering is acceptable, but it is important to
remain consistent when using arrays in algorithms.

Declaring the array in Visual Basic:

Dim Highscores(9) As Integer

Name of array Data type of


Size of array array

Specific data items can be placed in the array at the time of declaration (i.e. initialising the
array).

Prepared by K.Ramkissoon, St Joseph's College 2


Cambridge A & AS Level Computer Science 9618 Arrays

Declaring and initialising the array in pseudocode:

DECLARE Highscores : ARRAY[0:9] OF INTEGER // declaring

// 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 1: Each individual data item in the array is called an element.

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]

Declaring and initialising the array in Visual Basic:

Dim Highscores() As Integer = {83, 75, 77, 82, 95, 99, 84, 70, 91, 80}

Another way to declare and initialise the array in Visual Basic:

Dim Highscores = New Integer() {83, 75, 77, 82, 95, 99, 84, 70, 91, 80}

Prepared by K.Ramkissoon, St Joseph's College 3


Cambridge A & AS Level Computer Science 9618 Arrays

Diagrammatic representation of 1D array based on the above example

If index starts with 1:

Highscores
Index 1 83
2 75
3 77
4 82
5 95
6 99
7 84
8 70
9 91
10 80

If index starts with 0:

Highscores

Index 0 83
1 75
2 77
3 82
4 95
5 99
6 84
7 70
8 91
9 80

Note: A one-dimensional array (1D array) is also referred to as a list.

Prepared by K.Ramkissoon, St Joseph's College 4


Cambridge A & AS Level Computer Science 9618 Arrays

Declaring a variable-length array (i.e. it has no fixed size)

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.

An example of declaring variable-length array in pseudocode:

DECLARE Highscores : ARRAY[0:199] OF INTEGER

An example of declaring variable-length array in Visual Basic:

Dim Highscores(199) As Integer

Once we have created an array, we can then write data to the array or read data from it.

Reading from 1D array

We can ask a program to read certain elements in an array.


To do this, we would need to ask the program to output the data in location in an array.
The program will read the data in this location in the array and output it for us to see.

The following pseudocode outputs data items from the array Highscores created in the above
example.

OUTPUT Highscores[3]
OUTPUT Highscores[8]
OUTPUT Highscores[0]

Prepared by K.Ramkissoon, St Joseph's College 5


Cambridge A & AS Level Computer Science 9618 Arrays

Outputting data items from array in Visual Basic:

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.

Reading from an array using a variable as the index

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:

DECLARE Count : INTEGER


Count ← 3
OUTPUT Highscores[Count]

Reading data from the Highscores array using a variable as index in Visual Basic:

Dim Count As Integer = 3


Console.WriteLine(Highscores(Count))

If the variable Count held the value 3, this would output the data from the fourth element in the
array i.e. 82.

Prepared by K.Ramkissoon, St Joseph's College 6


Cambridge A & AS Level Computer Science 9618 Arrays

Reading from 1D array using loop / iteration

To read multiple values from an array, we can use a FOR … TO … NEXT loop.

Reading from the Highscores array using FOR loop in pseudocode:

DECLARE Count: INTEGER


FOR Count ← 0 TO 3
OUTPUT Highscores[Count]
NEXT Count

Reading from the Highscores array using FOR loop in Visual Basic:

Dim Count As Integer


For Count = 0 To 3
Console.WriteLine(Highscores(Count))
Next

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 pseudocode:

DECLARE Count: INTEGER


FOR Count ← 2 TO 7
OUTPUT Highscores[Count]
NEXT Count

Prepared by K.Ramkissoon, St Joseph's College 7


Cambridge A & AS Level Computer Science 9618 Arrays

Reading from the Highscores array not starting at index 0 in Visual Basic:

Dim Count As Integer


For Count = 2 To 7
Console.WriteLine(Highscores(Count))
Next

This loop would output the values 77, 82, 95, 99, 84 and 70.

Writing to 1D array (Populate array using loop / iteration)

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.

Writing to an empty array named Highscores in pseudocode:

DECLARE Highscores : ARRAY[0:9] OF INTEGER


DECLARE Count : INTEGER
FOR Count ← 0 TO 9
OUTPUT “Enter value: ”
INPUT Highscores[Count]
NEXT Count

Writing to an empty array named Highscores in Visual Basic:

Dim Highscores(9) As Integer


Dim Count As Integer
For Count = 0 To 9
Console.WriteLine("Enter highest score:")
Highscores(Count) = Console.ReadLine()
Next

Prepared by K.Ramkissoon, St Joseph's College 8


Cambridge A & AS Level Computer Science 9618 Arrays

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

Prepared by K.Ramkissoon, St Joseph's College 9


Cambridge A & AS Level Computer Science 9618 Arrays

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 pseudocode:

DECLARE Count : INTEGER


Count ← 3
Highscores[Count] ← 75

Updating data in the Highscores array using a variable as index in Visual Basic:

Dim Count As Integer = 3


Highscores(Count) = 75

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

Prepared by K.Ramkissoon, St Joseph's College 10


Cambridge A & AS Level Computer Science 9618 Arrays

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.

Prepared by K.Ramkissoon, St Joseph's College 11


Cambridge A & AS Level Computer Science 9618 Arrays

Pseudocode to search linearly through array of car makes:

Car ← [“Renault”, “Ford”, “Hyundai”, “Vauxhall”, “Audi”, “BMW”,


“Toyota”, “Citroen”, “Jaguar”]

DECLARE Carmake : STRING


DECLARE Count : INTEGER
Count ← 0
DECLARE Found : BOOLEAN
Found ← FALSE

OUTPUT “Enter car make: ”


INPUT Carmake

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)

IF Found = FALSE THEN


OUTPUT “Car make not found”
ENDIF

Prepared by K.Ramkissoon, St Joseph's College 12


Cambridge A & AS Level Computer Science 9618 Arrays

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

Console.WriteLine("Enter make of the car:")


Carmake = Console.ReadLine()

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)

If Found = False Then


Console.WriteLine("Car make not found")
End If

Prepared by K.Ramkissoon, St Joseph's College 13


Cambridge A & AS Level Computer Science 9618 Arrays

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

Console.WriteLine("Enter make of the car:")


Carmake = Console.ReadLine()

While (Found = False) And (Count < 9)


If Car(Count) = Carmake Then
Found = True
Console.WriteLine("Car make found at position " & Count)
End If
Count = Count + 1
End While

If Found = False Then


Console.WriteLine("Car make not found")
End If

Bubble Sort

• Bubble Sort is the simplest sorting algorithm.


• This sorting algorithm is comparison-based algorithm in which each pair of adjacent
elements is compared and the elements are swapped if they are not in order.
• The pass through the list is repeated until the list is sorted.
• Bubble Sort gets its name because smaller elements bubble towards the top of the list.
• We can also use bubble sort to arrange the elements in an array in either ascending or
descending order.

Prepared by K.Ramkissoon, St Joseph's College 14


Cambridge A & AS Level Computer Science 9618 Arrays

Example

Consider an array of numbers “-5, 72, 0, 33, -9”.


We sort the array from the lowest number to the greatest number using bubble sort.
In each step, elements written in bold are being compared.

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

(-5 -9 0 33 72) → (-9 -5 0 33 72), swap since -5 > -9


(-9 -5 0 33 72) → (-9 -5 0 33 72), no swap (because -5 < 0)
(-9 -5 0 33 72) → (-9 -5 0 33 72), no swap (because 0 < 33)
(-9 -5 0 33 72) → (-9 -5 0 33 72), no swap (because 33 < 72) and now the array is already sorted

Prepared by K.Ramkissoon, St Joseph's College 15


Cambridge A & AS Level Computer Science 9618 Arrays

Pseudocode to bubble sort array [-5, 72, 0, 33, -9] using repeat until loop:

Number ← [-5, 72, 0, 33, -9]

DECLARE Index, Temp : INTEGER


DECLARE ArraySize : INTEGER
ArraySize ← 4
DECLARE Swapped : BOOLEAN

REPEAT // outer loop starts a new pass, in all 4 passes


Swapped ← FALSE
FOR Index ← 0 TO ArraySize-1 // i.e. 0 to 3 = 4 times
// Inner for loop repeats comparison of adjacent elements
IF Number[Index] > Number[Index+1] THEN // compares
adjacent elements
// Swap them
Temp ← Number[Index]
Number[Index] ← Number[Index+1]
Number[Index+1] ← Temp
Swapped ← TRUE
ENDIF
NEXT Index
ArraySize ← ArraySize – 1 // to move through the values to
compare next adjacent value
after completing previous one
UNTIL (NOT Swapped) OR ArraySize = 0

FOR Index ← 0 TO 4
OUTPUT Number[Index] // outputs -9, -5, 0, 33, 72
NEXT Index

Prepared by K.Ramkissoon, St Joseph's College 16


Cambridge A & AS Level Computer Science 9618 Arrays

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

Do ' outer loop starts a new pass, in all 4 passes


Swapped = False
For Index = 0 To ArraySize-1 '0 to 3 = 4 times
' Inner for loop repeats comparison of adjacent elements
If Number(Index) > Number(Index+1) Then 'compares adjacent elements
' Swap them
Temp = Number(Index)
Number(Index) = Number(Index+1)
Number(Index+1) = Temp
Swapped = True
End If
Next
ArraySize = ArraySize-1 ' to move through the values to compare next adjacent
value after completing previous one
Loop Until (Not Swapped) Or ArraySize = 0

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.

Prepared by K.Ramkissoon, St Joseph's College 17


Cambridge A & AS Level Computer Science 9618 Arrays

Pseudocode to bubble sort array [-5, 72, 0, 33, -9] using nested FOR loops:

Number ← [-5, 72, 0, 33, -9]


DECLARE Count : INTEGER
DECLARE ArraySize : INTEGER
ArraySize ← 4
DECLARE Swapped : BOOLEAN
Swapped ← FALSE
DECLARE i : INTEGER
DECLARE j : INTEGER
DECLARE Temp : INTEGER

FOR i ← 0 TO ArraySize-1 // The outer for loop starts a new pass


FOR j ← 0 TO ArraySize-1 // Inner for loop repeats
comparison of adjacent elements
IF Number[j] > Number[j+1] THEN // Compare the adjacent
elements
// Swap them
Temp ← Number[j]
Number[j] ← Number[j+1]
Number[j+1] ← Temp
Swapped ← TRUE
ENDIF
NEXT j
//If no number was swapped that means array is sorted now, break
the loop.
IF (NOT Swapped) THEN
EXIT PROGRAM
ENDIF
NEXT i

FOR Count ← 0 TO 4
OUTPUT Number[Count] // outputs -9, -5, 0, 33, 72
NEXT Count

Prepared by K.Ramkissoon, St Joseph's College 18


Cambridge A & AS Level Computer Science 9618 Arrays

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

For i = 0 To ArraySize-1 ' Outer for loop starts a new pass


For j = 0 To ArraySize-1 ' Inner for loop repeats comparison of adjacent elements
If Number(j) > Number(j+1) Then ' Compare the adjacent elements
' Swap them
Temp = Number(j)
Number(j) = Number(j+1)
Number(j+1) = Temp
Swapped = True
End If
Next

' 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

Prepared by K.Ramkissoon, St Joseph's College 19


Cambridge A & AS Level Computer Science 9618 Arrays

Two-Dimensional Array (2D Array)

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

Consider the 2D array named Board below.

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

Columns Last element in


2D array

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.

Prepared by K.Ramkissoon, St Joseph's College 20


Cambridge A & AS Level Computer Science 9618 Arrays

Declaring the 2D array Board in pseudocode:

DECLARE Board : ARRAY[0:9, 0:2] OF INTEGER

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

Declaring the 2D array Board in Visual Basic:

Here, we assume the array is empty.

Dim Board(9,2) As Integer

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:

DECLARE RowCounter, ColumnCounter : INTEGER


DECLARE Board : ARRAY[0:9, 0:2] OF INTEGER

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

OUTPUT “Number at location (4, 1) is ” ,Board(4, 1))


// to check if it outputs the correct element i.e. 90

Prepared by K.Ramkissoon, St Joseph's College 21


Cambridge A & AS Level Computer Science 9618 Arrays

Visual Basic to populate the 2D array Board with the numbers as they are on Page 20:

Dim RowCounter, ColumnCounter As Integer


Dim Board(9, 2) As Integer

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

Console.WriteLine("Number at location (4, 1) is " & Board(4, 1))


' to check if it outputs the correct element i.e. 90

Another way to populate the 2D array Board in Visual Basic:

Declare and initialise the 2D array:

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}}

Console.WriteLine("Number at location (4, 1) is " & Board(4, 1))


' to check if it outputs the correct element i.e. 90

Prepared by K.Ramkissoon, St Joseph's College 22


Cambridge A & AS Level Computer Science 9618 Arrays

Advantages of using arrays

• 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.

Disadvantages of using arrays

• 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).

Example questions on arrays

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:

Number ← [12, 14, 10, 6, 7, 11, 3]


DECLARE Sum : INTEGER
DECLARE Average : REAL
DECLARE Count : INTEGER
Sum ← 0

FOR Count ← 0 TO 6
Sum ← Sum + Number[Count]
NEXT Count

Average ← Sum/Count
OUTPUT “The average is ” , Average

Prepared by K.Ramkissoon, St Joseph's College 23


Cambridge A & AS Level Computer Science 9618 Arrays

Visual Basic:

Dim Number() As Integer = {12, 14, 10, 6, 7, 11, 3}


Dim Sum As Integer = 0
Dim Average As Decimal
Dim Count As Integer

For Count = 0 To 6
Sum = Sum + Number(Count)
Next

Average = Sum/Count
Console.WriteLine(“The average is ” & Average)

Passing a 1D array as parameter in procedure and function

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.

Prepared by K.Ramkissoon, St Joseph's College 24


Cambridge A & AS Level Computer Science 9618 Arrays

Pseudocode (Using procedure):

PROCEDURE Calcaverage(BYVAL Arraynum[]: INTEGER, BYREF Average: REAL)


DECLARE Sum : INTEGER
DECLARE Count : INTEGER
Sum ← 0
FOR Count ← 0 TO 6
Sum ← Sum + Arraynum[Count]
NEXT Count
Average ← Sum/Count
ENDPROCEDURE

// 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

Visual Basic (Using procedure):

Sub Calcaverage(ByVal Arraynum() As Integer, ByRef Average As Decimal)


Dim Sum As Integer = 0
Dim Count As Integer
For Count = 0 To 6
Sum = Sum + Arraynum(Count)
Next
Average = Sum/Count
End Sub

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

Prepared by K.Ramkissoon, St Joseph's College 25


Cambridge A & AS Level Computer Science 9618 Arrays

Pseudocode (Using function):

FUNCTION Calcaverage(Arraynum[]: INTEGER) RETURNS REAL


DECLARE Sum : INTEGER
DECLARE Count : INTEGER
Sum ← 0
FOR Count ← 0 TO 6
Sum ← Sum + Arraynum[Count]
NEXT Count
RETURN Sum/Count
ENDFUNCTION

// Main program
Number ← [12, 14, 10, 6, 7, 11, 3]
OUTPUT “The average is ” , Calcaverage(Number)
// End of main program

Visual Basic (Using function):

Function Calcaverage(Arraynum() As Integer) As Decimal


Dim Sum As Integer = 0
Dim Count As Integer
For Count = 0 To 6
Sum = Sum + Arraynum(Count)
Next
Return Sum/Count
End Function

Sub Main()
Dim Number() As Integer = {12, 14, 10, 6, 7, 11, 3}
Console.WriteLine(“The average is ” & Calcaverage(Number))
End Sub

Prepared by K.Ramkissoon, St Joseph's College 26


Cambridge A & AS Level Computer Science 9618 Arrays

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.

Your algorithm / program should output


(i) the number of teenagers who are taller than 1.5 metres.
(ii) the smallest shoe size.

All identifiers should have meaningful names.

Prepared by K.Ramkissoon, St Joseph's College 27


Cambridge A & AS Level Computer Science 9618 Arrays

Pseudocode:

DECLARE Height : ARRAY[1:30] OF REAL


DECLARE Shoesize : ARRAY[1:30] OF REAL
DECLARE Minsize : REAL
DECLARE CountTall : INTEGER
DECLARE Count : INTEGER
Minsize ← 100
CountTall ← 0

FOR Count ← 1 TO 30
OUTPUT “Enter height: ”
INPUT Height[Count]

OUTPUT “Enter shoesize: ”


INPUT Shoesize[Count]

IF Height[Count] > 1.5 THEN


CountTall ← CountTall + 1
ENDIF

IF Shoesize[Count] < Minsize THEN


Minsize ← Shoesize[Count]
ENDIF
NEXT Count

OUTPUT “No of teenagers taller than 1.5: ” , CountTall


OUTPUT “Smallest shoe size: ” , Minsize

Prepared by K.Ramkissoon, St Joseph's College 28


Cambridge A & AS Level Computer Science 9618 Arrays

Visual Basic:

Note: For the purpose of testing, the array size has been set to 4.

Dim Height(4) As Decimal


Dim Shoesize(4) As Decimal
Dim Minsize As Decimal = 100
Dim CountTall As Integer = 0
Dim Count As Integer

For count = 1 To 4
Console.WriteLine("Enter height: ")
Height(Count) = Console.ReadLine()

Console.WriteLine("Enter shoesize: ")


Shoesize(Count) = Console.ReadLine()

If Height(Count) > 1.5 Then


CountTall = CountTall + 1
End If

If Shoesize(Count) < Minsize Then


Minsize = Shoesize(Count)
End If
Next

Console.WriteLine("No of teenagers taller than 1.5: " & CountTall)


Console.WriteLine("Smallest shoes size: " & Minsize)

Prepared by K.Ramkissoon, St Joseph's College 29


Cambridge A & AS Level Computer Science 9618 Arrays

Question 3

Input and store the names and marks for 30 students who have sat three computer science tests.

Test1 is out of 20 marks


Test2 is out of 25 marks
Test3 is out of 35 marks

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.

• Calculate and store the total score for each student.


• Calculate the average score for the whole class.
• Output each student's name followed by their total score, then output the average score
for the class.
• Select the student with the highest score and output their name and score.

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.

Prepared by K.Ramkissoon, St Joseph's College 30


Cambridge A & AS Level Computer Science 9618 Arrays

Visual Basic:

Note: For the purpose of testing, the array size has been set to 2.

Dim Names(2) As String


Dim Test1(2) As Integer
Dim Test2(2) As Integer
Dim Test3(2) As Integer
Dim Total(2) As Integer
Dim Classtotal As Integer = 0
Dim Classavg As Decimal

Dim Maxscore As Integer = 0


Dim Maxname As String

Dim Count As Integer

For Count = 0 To 2

Console.WriteLine("Enter name of student:")


Names(Count) = Console.ReadLine()

Do
Console.WriteLine("Enter marks for test1:")
Test1(Count) = Console.ReadLine()

If Test1(Count) < 0 Or Test1(Count) > 20 Then


Console.WriteLine("Invalid marks! Marks should be from 0 to 20.")
End If
Loop Until Test1(Count) >=0 And Test1(Count) <=20

Do
Console.WriteLine("Enter marks for test2:")
Test2(Count) = Console.ReadLine()

If Test2(Count) < 0 Or Test2(Count) > 25 Then


Console.WriteLine("Invalid marks! Marks should be from 0 to 25.")
End If
Loop Until Test2(Count) >=0 And Test2(Count) <=25

Do
Console.WriteLine("Enter marks for test3:")
Test3(Count) = Console.ReadLine()

If Test3(Count) < 0 Or Test3(Count) > 35 Then


Console.WriteLine("Invalid marks! Marks should be from 0 to 35.")
End If
Loop Until Test3(Count) >=0 And Test3(Count) <=35

Prepared by K.Ramkissoon, St Joseph's College 31


Cambridge A & AS Level Computer Science 9618 Arrays

Total(Count) = Test1(Count) + Test2(Count) + Test3(Count)

Console.WriteLine("Total score of student " & Names(Count) & " is " & Total(Count))

Classtotal = Classtotal + Total(Count)

If Total(Count) > Maxscore Then


Maxscore = Total(Count)
Maxname = Names(Count)
End if

Next

Classavg = Classtotal/Count

Console.WriteLine("The average score for the class is " & Classavg)


Console.WriteLine("Student " & Maxname & " scores the highest marks of " & Maxscore)

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.

1.3 7.5 -3.2 4.8


6.2 -10.5 14.7 18.3
-11.5 -20.2 6.8 9.7
15.6 5.9 16 7
-19.2 13.3 2.5 4.4

Prepared by K.Ramkissoon, St Joseph's College 32


Cambridge A & AS Level Computer Science 9618 Arrays

Pseudocode:

DECLARE RowCounter, ColumnCounter : INTEGER


DECLARE NumberArray : ARRAY[1:5, 1:4] OF REAL
DECLARE Average, Total, Largest, Smallest : REAL
Total ← 0
Largest ← -100000.0
Smallest ← 100000.0
FOR RowCounter ← 1 TO 5
FOR ColumnCounter ← 1 TO 4
OUTPUT “Enter the numbers column wise i.e. input 1.3 and
press enter, then input 6.2 and press enter, etc : ”
INPUT NumberArray[RowCounter, ColumnCounter]

Total ← Total + NumberArray[RowCounter, ColumnCounter]

IF NumberArray[RowCounter, ColumnCounter] < Smallest


THEN
Smallest ← NumberArray[RowCounter, ColumnCounter]
ENDIF

IF NumberArray[RowCounter, ColumnCounter] > Largest


THEN
Largest ← NumberArray[RowCounter, ColumnCounter]
ENDIF
NEXT ColumnCounter
NEXT RowCounter

Average ← Total/20

OUTPUT “Average is ” , Average


OUTPUT “Smallest value is ” , Smallest
OUTPUT “Largest value is ” , Largest

Prepared by K.Ramkissoon, St Joseph's College 33


Cambridge A & AS Level Computer Science 9618 Arrays

Visual Basic:

Dim RowCounter, ColumnCounter As Integer


Dim NumberArray(5, 4) As Decimal ' index starts with 1
Dim Average As Decimal
Dim Total As Decimal = 0
Dim Largest As Decimal = -100000.0
Dim Smallest As Decimal = 100000.0

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()

Total = Total + NumberArray(RowCounter, ColumnCounter)

If NumberArray(RowCounter, ColumnCounter) < Smallest Then


Smallest = NumberArray(RowCounter, ColumnCounter)
End If

If NumberArray(RowCounter, ColumnCounter) > Largest Then


Largest = NumberArray(RowCounter, ColumnCounter)
End If
Next
Next

Average = Total/20

Console.WriteLine("Average is " & Average)


Console.WriteLine("Smallest value is " & Smallest)
Console.WriteLine("Largest value is " & Largest)

Prepared by K.Ramkissoon, St Joseph's College 34


Cambridge A & AS Level Computer Science 9618 Arrays

Passing a 2D array as parameter in procedure and function

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.

Pseudocode (Using procedure):

PROCEDURE Calcaverage(BYVAL Arraynum[,]: INTEGER, BYREF Average:


REAL)
DECLARE Sum : INTEGER
DECLARE Rowcount, Columncount : INTEGER
Sum ← 0
FOR Rowcount ← 0 TO 4
FOR Columncount ← 0 TO 3
Sum ← Sum + Arraynum[Rowcount, Columncount]
Next Columncount
NEXT Rowcount
Average ← Sum/20
ENDPROCEDURE

// 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

Prepared by K.Ramkissoon, St Joseph's College 35


Cambridge A & AS Level Computer Science 9618 Arrays

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

DECLARE Ave : REAL


CALL Calcaverage(Number, Ave)
OUTPUT “The average is ” , Ave
// End of main program

Visual Basic (Using procedure):

Sub Calcaverage(ByVal Arraynum(,) As Integer, ByRef Average As Decimal)


Dim Sum As Integer = 0
Dim Rowcount, Columncount As Integer
For Rowcount = 0 To 4
For Columncount = 0 To 3
Sum = Sum + Arraynum(Rowcount, Columncount)
Next
Next
Average = Sum/20
End Sub

Sub Main()
Dim Number(4, 3) As Integer
Number(0,0) = 1.3
Number(0,1) = 7.5
Number(0,2) = -3.2

Prepared by K.Ramkissoon, St Joseph's College 36


Cambridge A & AS Level Computer Science 9618 Arrays

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

Prepared by K.Ramkissoon, St Joseph's College 37


Cambridge A & AS Level Computer Science 9618 Arrays

Pseudocode (Using function):

FUNCTION Calcaverage(Arraynum[,]: INTEGER) RETURNS REAL


DECLARE Sum : INTEGER
DECLARE Rowcount, Columncount : INTEGER
Sum ← 0
FOR Rowcount ← 0 TO 4
FOR Columncount ← 0 TO 3
Sum ← Sum + Arraynum[Rowcount, Columncount]
NEXT Columncount
NEXT Rowcount
RETURN Sum/20
ENDFUNCTION

// 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

Prepared by K.Ramkissoon, St Joseph's College 38


Cambridge A & AS Level Computer Science 9618 Arrays

Number[4,1] ← 13.3
Number[4,2] ← 2.5
Number[4,3] ← 4.4

OUTPUT “The average is ” , Calcaverage(Number)


// End of main program

Visual Basic (Using function):

Function Calcaverage(Arraynum(,) As Integer) As Decimal


Dim Sum As Integer = 0
Dim Rowcount, Columncount As Integer
For Rowcount = 0 To 4
For Columncount = 0 To 3
Sum = Sum + Arraynum(Rowcount, Columncount)
Next
Next
Return Sum/20
End Function

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

Prepared by K.Ramkissoon, St Joseph's College 39


Cambridge A & AS Level Computer Science 9618 Arrays

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

Console.WriteLine(“The average is ” & Calcaverage(Number))


End Sub

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

LANGFIELD, S. and DUDDELL, D. (2015) Cambridge International AS and A Level Computer


Science Coursebook. United Kingdom: Cambridge University Press.

LANGFIELD, S. and DUDDELL, D. (2019) Cambridge International AS and A Level Computer


Science Coursebook 2nd ed. United Kingdom: Cambridge University Press.

PIPER, T. (2016) Cambridge International AS and A Level Computer Science Revision Guide.
United Kingdom: Cambridge University Press.

WATSON, D. and WILLIAMS, H. (2019) Cambridge International AS & A Level Computer


Science. London: Hodder Education

Prepared by K.Ramkissoon, St Joseph's College 40


Cambridge A & AS Level Computer Science 9618 Arrays

(2019) Fundamentals of Programming: One-Dimensional Arrays [WWW] Wikibooks. Available


from: https://en.wikibooks.org/wiki/A-
level_Computing/AQA/Problem_Solving,_Programming,_Data_Representation_and_Practical_Exe
rcise/Fundamentals_of_Programming/One-Dimensional_Arrays [Accessed 20/01/19]

(2019) Fundamentals of Programming: Two-Dimensional Arrays [WWW] Wikibooks. Available


from: https://en.wikibooks.org/wiki/A-
level_Computing/AQA/Problem_Solving,_Programming,_Data_Representation_and_Practical_Exe
rcise/Fundamentals_of_Programming/Two-Dimensional_Arrays [Accessed 20/01/19]

(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) Bubble Sort [WWW] GeeksforGeeks. Available from:


https://www.geeksforgeeks.org/bubble-sort/ [Accessed 20/01/19]

(2019) Bubble sort [WWW] Wikipedia. Available from: https://en.wikipedia.org/wiki/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]

Prepared by K.Ramkissoon, St Joseph's College 41


Cambridge A & AS Level Computer Science 9618 Arrays

(2019) Linear Search [WWW] GeeksforGeeks. Available from:


https://www.geeksforgeeks.org/linear-search/ [Accessed 21/01/19]

(2019) Linear search in C [WWW] Programming Simplified. Available from:


https://www.programmingsimplified.com/c/source-code/c-program-linear-search [Accessed
21/01/19]

Working with Arrays [WWW] Available from: https://www.thevbprogrammer.com/VB2010_07/07-


01-Arrays1.htm [Accessed 31/08/24]

Prepared by K.Ramkissoon, St Joseph's College 42

You might also like