登录

Arrays

Syllabus requirements

The Cambridge International AS & A Level syllabus (9618) requires candidates to understand and use both one-dimensional and two-dimensional arrays.

Declaring arrays

Arrays are considered to be fixed-length structures of elements of identical data type, accessible by consecutive index (subscript) numbers.

It is good practice to explicitly state what the lower bound of the array (i.e. the index of the first element) is because this defaults to either 0 or 1 in different systems. Generally, a lower bound of 1 will be used.

Square brackets are used to indicate the array indices. A One-dimensional array is declared as follows:

DECLARE <identifier> : ARRAY[<lower>:<upper>] OF <datatype>

A two-dimensional array is declared as follows:

DECLARE <identifier> : ARRAY[<lower1> : <upper1>,<lower2> : <upper2>] OF <data type>
//Example – array declarations
DECLARE StudentNames : ARRAY[1:30] OF STRING
DECLARE NoughtsAndCrosses : ARRAY[1:3,1:3] OF CHAR

Using arrays

Array index values may be literal values or expressions that evaluate to a valid integer value.

//Example – Accessing individual array elements
StudentNames[1] ← "Ali"
NoughtsAndCrosses[2,3] ← ꞌXꞌ
StudentNames[n+1] ← StudentNames[n]

Arrays can be used in assignment statements (provided they have same size and data type). The following is therefore allowed:

//Example – Accessing a complete array
SavedGame ← NoughtsAndCrosses

A statement should not refer to a group of array elements individually. For example, the following construction should not be used.

StudentNames [1 TO 30] ← "Tom"

Instead, an appropriate loop structure is used to assign the elements individually. For example:

//Example – assigning a group of array elements
FOR Index ← 1 TO 30
    StudentNames[Index] ← "Tom"
NEXT Index

  • An element in the list can be read using the list name + [index].

1D Array


colors = ['red', 'green', 'blue', 'yellow', 'white', 'black']
print(colors[0]) #red
print(colors[1]) #green
print(colors[2]) #blue

2D Array

numbers_1d = [1,2,3]
numbers_2d = [[1,2,3],[4,5,6],[7,8,9]]
numbers_2d = [[1,2,3],[4,5,6],[7,8,9]]
numbers = numbers_2d[0]
print(numbers) #[1, 2, 3]
print(numbers[0]) #1
print(numbers_2d[0][0]) #1
Zero

The index of the list must start at 0, which is the easiest point for beginners to forget.

登录