Arrays in Pascal consist of contiguous array elements in memory. The lowest address corresponds to the first element, and the highest address corresponds to the last element.
Note that if you want a C-style array to start from index 0, you simply need to input the first index as 0, instead of 1.
Declaring Arrays in Pascal
To declare an array in Pascal, programmers can declare the type first, then create variables for that array or directly declare the array variables.
The general structure of declaring a one-dimensional array in Pascal is as follows:
type
array-identifier = array[index-type] of element-type;
Where:
- array-identifier: represents the name of the array type.
- index-type:
- element-type: specifies the types of values to be stored.
For example:
Where velocity is an array variable of vectors, capable of holding up to 25 real numbers.
If starting the array from index 0, the declaration would be as follows:
Types of Array Subscripts in Pascal
In Pascal, an array subscript can be a scalar data type of integer, Boolean, enumerated, or subrange, except for real. Array subscripts can have negative values.
For example:
Here is an array subscript of type character:
Subscripts of type enumerated:
Initializing Arrays in Pascal
In Pascal, arrays are initialized either by assignment or by specifying a specific subscript or using a for-do loop.
For instance:
Accessing Array Elements in Pascal
Array elements in Pascal are accessed by indexing the array name. This is done by placing the index of the element inside square brackets after the array name.
For example:
a: integer;
a: = alphabet['A'];
The above command will retrieve the first element from the array named alphabet and assign the value to the variable a.
Below is another example, demonstrating array declaration, assignment, and accessing:
When the above code segment is compiled and executed, it will return the following result:
Details of Arrays in Pascal
This article introduces you to arrays in Pascal as well as how arrays are declared, initialized in Pascal. Furthermore, to delve deeper into operators in Pascal or constants and how constants are declared in Pascal, readers can refer to some articles already available on Mytour.