Arrays

An array is a list of variables of the same type. Individual members of the list are referred to by specifying the list's name and a position (or index) within it. For example,

var Number : array [1..10] of real;

tells the compiler that variable Number is a list of ten real variables. Each element of an array is referred to by the name of the array, followed by its index (position) enclosed in brackets. Thus, array Number contains 10 unique variables: Number[1], Number[2], Number[3], Number[4], Number[5], Number[6], Number[7], Number[8], Number[9], and Number[10]. You can use any of these variables wherever you would use a regular real variable. Furthermore--and this is what makes arrays useful--the index value can be any expression that yields an integer in the range 1..10. For example, if variable J is of the type integer, this for loop

for J := 1 to 10 do Number[J] := 0.0;

zeros each variable.

Arrays can be multidimensional; that is, arrays of arrays (of arrays...) can be created:

var YearlyHighs = array[1..12] of array[1..31] of integer;

which is the same as

YearlyHighs = array[1..12][1..31] of integer;

and, in shorthand form:

YearlyHighs = array[1..12, 1..31] of integer;

Such an array must be indexed with two integers:

Writeln('The hottest it ever got on December 25 is ', YearlyHighs[12,25]);
program ArrayDemo;

uses
Win32Crt;

const
maxrolls = 50000;

var

Counts: array[2..12] of longint;
RollCount : longint;
N: integer;
ThisRoll: integer;
MostPopularRoll: integer;
HighestTotalSoFar: longint;
C: char;


function RollEm: integer; { Rolls dice }
begin

RollEm := Random(6) + Random(6) + 2;

end; { RollEm }

begin { ArrayDemo }

Randomize;
RollCount := 0;
for N := 2 to 12 do Counts[n] := 0; { initialize the array }
while not KeyPressed do
begin

RollCount := RollCount + 1;
ThisRoll := RollEm;
Counts[ThisRoll] := Counts[ThisRoll] + 1;

end;
C := ReadKey;
{ absorb the keystroke }
Writeln('After: ', RollCount, ' Rolls');
Writeln(' # Count ');
for N := 2 to 12 do Writeln(n:2, ' ', Counts[n]:7);

{ Now search for the most popular number }


HighestTotalSoFar := 0;
for N := 2 to 12 do if Counts[N] > HighestTotalSoFar then
begin

HighestTotalSoFar := Counts[N];
MostPopularRoll := N

end;
Writeln('The most popular roll is ', MostPopularRoll);

end. { ArrayDemo }

 
Send mail to ljschwerin@hotmail.com with questions or comments about this web site.

Copyright © 1999-2002 Leon Schwerin
Last modified: 04 March 2002
1