Arrays

We have covered the data types integer, string, char and Boolean. An array is a data structure used to store data items of the same type. In the example below an array is used to store the monthly rainfall of a place in a single year:

var
  Rainfall : array [1 .. 12] of integer;
      

Array declarations must show the identifier (in this case Rainfall), the bounds (a start value of 1 and an end value of 12) and the type (integer).

To identify individual members of the array, the index (also known as subscript) is given in square brackets. The statement

  Rainfall[2] := 30;

uses the index 2 to assign the value 30 to the second integer in the array (representing February).

This array is used to input monthly rainfall in the following program.

program  MonthlyRainfall;
{$APPTYPE CONSOLE}
var
  Rainfall : array [1 .. 12] of integer;
  Count, Total : integer;
begin
  for Count := 1 to 12 do
    begin
       write('Please enter rainfall for month ', Count, ' ');
       readln(Rainfall[Count]);
    end; 
  Total := 0;
  writeln; 
  writeln ('Rainfall stored:');
  for Count := 1 to 12 do
    begin
      writeln('Month ', Count, ': ', Rainfall[Count], ' ');
      Total := Total + Rainfall[Count];
    end;
  writeln;
  writeln('Total for year: ', Total);
  readln;
end.

A string can be treated as an array of char, so that if MyString := 'Computing', MyString[3] is 'm'.

Features introduced:
  • Vocabulary : the identifier, bounds, type and index of an array
  • Array declaration
  • Data input to an array
  • Processing an array
  • Treating a string as an array

Now take a look at some more types of array by following the links below. Study our advanced tutorial on arrays when you are a confident programmer.

Programming - a skill for life!

Pascal Programming Tutorials