An array is a fixed-sized collection of data of the same type. Arrays are assigned a contiguous block of memory and are declared as follows:
_arrayName_ = array [_subscript_] of _dataType_;
_arrayName_
: The name of the array that identifies the array._subscript_
: The index of the array; _subscript_
can be of any ordinal type. The array subscript cannot be real._dataType_
: The data type of the elements of the array.To access an element of the array at an index, use the subscript operator, as shown below:
elem := arr[ind];
elem
is the element of arrayarr
at indexind
.
To assign a value to an element of the array at a specific index, use the =:
operator, as shown below:
arr[ind] = x;
The code snippet above assigns the value x
to the array element at index ind
.
Consider the code snippet below, which demonstrates the declaration of an integer array.
program arrayExample1;vararr: array [0..4] of integer;i: integer;begin{assigning values to elements of array}for i := 0 to 4 doarr[i] := i * i;{printing elements of array}for i:= 0 to 4 dowriteln('arr[', i, '] = ', arr[i] );end.
An array of integers is declared in line 3. Values are assigned to elements of the array in line 9. The array elements are printed in line 13.
Consider the code snippet below, which uses char
as an array index:
program arrayExample2;vararr: array [char] of integer;i: char;j: integer;beginj := 1;{assigning values to elements of array}for i := 'a' to 'z' dobeginarr[i] := j;j := j + 1;end;{printing elements of array}for i := 'a' to 'z' dowriteln('arr[', i, '] = ', arr[i] );end.
char
is used as an array index type. a
accesses the first element of the array, b
accesses the second element of the array, c
accesses the third element of the array, and so on.