Array Parameters

Before we discuss open array parameters we cover the situation where your procedure always uses the same size of array. You can define that size as a type and use that type for an array parameter. Program ArrayParamDemo is a short contrived example that shows you how.

program ArrayParamDemo;
type
  TArray15 = array[0 .. 14] of integer;
var
  FibNums, Cubes : TArray15;
  i : integer;

procedure Display(DisplayedArray : TArray15; strText : string);
var
  i : integer;
begin
  writeln;
  for i := 0 to 14 do
    writeln(strText,' ', i, ': ', DisplayedArray[i]);
end;

begin
  FibNums[0] := 0;
  FibNums[1] := 1;
  for i := 2 to 14 do
    FibNums[i] :=  FibNums[i - 1] + FibNums[i - 2];
  for i := 0 to 14 do
    Cubes[i] := i * i * i;
  writeln('This program will store temporarily the values of Fibonacci numbers' +
          'and cubes in arrays then display them.');
  Display(FibNums, 'Fibonacci');
  Display(Cubes, 'Cube of ');
  readln;
end.

If you want to use a procedure that accepts different sizes of array, you can use an open array parameter. The open array is always zero-based and the high function returns the index of the last item in the array. Program OpenArrayParamDemo shows you how to use an open array parameter and illustrates the high function.

program OpenArrayParamDemo;
var
  FibNums : array[0 .. 14] of integer;
  Cubes : array[0 .. 10] of integer;
  i : integer;

procedure Display(DisplayedArray : array of integer; strText : string);
var
  i : integer;
begin
  writeln;
  for i := 0 to high(DisplayedArray) do
    writeln(strText,' ', i, ': ', DisplayedArray[i]);
end;

begin
  FibNums[0] := 0;
  FibNums[1] := 1;
  for i := 2 to 14 do
    FibNums[i] :=  FibNums[i - 1] + FibNums[i - 2];
  for i := 0 to 10 do
    Cubes[i] := i * i * i;
  writeln('This program will store temporarily the values of Fibonacci numbers' +
          'and cubes in arrays then display them.');
  Display(FibNums, 'Fibonacci');
  Display(Cubes, 'Cube of ');
  readln;
end.
Programming - a skill for life!

Further ways of using arrays for confident programmers