Two-Dimensional Arrays

A two-dimensional array is also known as a table. The previous example program can be extended to include a two-dimensional array of integer to record the rainfall for several years. It is good practice to initialise the arrays before use. In program Rainfall3, the monthly rainfall for the years 2008 to 2010 is initialised to 0 before any data is input. This uses nested loops.

program  MonthlyRainfall3;
{$APPTYPE CONSOLE}
const
   MonthNames : array [1..12] of string = ('January', 'February', 'March', 'April', 'May', 'June',
                                  'July',  'August', 'September', 'October', 'November', 'December');
var
  Rainfall : array [1..12, 2008..2010] of integer;
  Month, Year, Total : integer;
begin
//initialise all array items to 0  
  for Month  := 1 to 12 do
    begin
      for Year := 2008 to 2010 do
        begin
          Rainfall[Month, Year] := 0;
        end;
    end; 
  //Just enter data for 1 year
  for Month  := 1 to 12 do
    begin
      write('Please enter rainfall for ', MonthNames[Month], ' in 2008 ');
      readln(Rainfall[Month, 2008]);
    end; 

  Total := 0;
  writeln; 
  writeln ('Rainfall stored for 2008:');
  for Month  := 1 to 12 do
    begin
      writeln(MonthNames[Month], ': ', Rainfall[Month, 2008], ' ');
      Total := Total + Rainfall[Month, 2008];
    end;
  writeln;
  writeln('Total for 2008: ', Total);
  readln;
end.
Features introduced:
  • Two-dimensional array declaration
  • Initialising two-dimensional arrays
  • Data input to two-dimensional arrays
  • Processing two-dimensional arrays
Programming - a skill for life!

How to declare and use arrays