Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pascal
array

How to declare arrays in Pascal

Kainat Asif

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.

Access an element 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 array arr at index ind.

Assign values to elements of the array

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.

Examples

Example 1

Consider the code snippet below, which demonstrates the declaration of an integer array.

program arrayExample1;
var
   arr: array [0..4] of integer;   
   i: integer;
 
begin  
   {assigning values to elements of array}      
   for i := 0 to 4 do
       arr[i] := i * i;  

   {printing elements of array}
   for i:= 0 to 4 do
      writeln('arr[', i, '] = ', arr[i] );
end.

Explanation

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.

Example 2

Consider the code snippet below, which uses char as an array index:

program arrayExample2;
var
   arr: array [char] of integer;   
   i: char;
   j: integer;
 
begin  
   j := 1;
   {assigning values to elements of array}      
   for i := 'a' to 'z' do
   begin
       arr[i] := j; 
       j := j + 1;
   end;

   {printing elements of array}
   for i := 'a' to 'z' do
      writeln('arr[', i, '] = ', arr[i] );
end.

Explanation

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.

RELATED TAGS

pascal
array

CONTRIBUTOR

Kainat Asif
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring