登录

Arrays

Declaring arrays

Arrays are fixed-length structures of elements of identical data type, accessible by consecutive index 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. 1D and 2D arrays are declared as follows (where l, l1, l2 are lower bounds and u, u1, u2 are upper bounds):

DECLARE <identifier> : ARRAY[<l>:<u>] OF <data type>
DECLARE <identifier> : ARRAY[<l1>:<u1>, <l2>:<u2>] OF <data type>

Example – array declaration

DECLARE StudentNames : ARRAY[1:30] OF STRING
DECLARE NoughtsAndCrosses : ARRAY[1:3, 1:3] OF CHAR

Using arrays

In the main pseudocode statements, only one index value is used for each dimension in the square brackets.

Example – using arrays

StudentNames[1] ← "Ali"
NoughtsAndCrosses[2,3] ← ꞌXꞌ
StudentNames[n+1] ← StudentNames[n]

An appropriate loop structure is used to assign the elements individually.

Example – assigning a group of array elements

FOR Index ← 1 TO 30
    StudentNames[Index] ← ""
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.

登录