header image
Home arrow Programming arrow Arrays
Arrays

An array variable can be used to store many data items of the same kind under the same name.  Each item is distinguished from the other using an index.

Arrays must be declared under the var and a range must be set, for example:
var
  arrNames : array[1..20] of String;
  arrAges : array[1.1000] of Integer;


The array arrNames can contain up to 20 names (String data type).
The array arrAges can contain up to 1000 integer values.

Dynamic arrays are used in instances where there is no clear indication of how many items will be used initially.

Data is usually entered into an array using a loop, for example:
var
 Form1: TForm1;
 arrNum : array[1..10] of Integer;

implementation

{$R *.DFM}

procedure TForm1.btnEnterNumClick(Sender: TObject);
var
 iCount : Integer;
begin
 FOR iCount := 1 to 10 do
 begin
  arrNum[iCount] := iCount * 2;
 end;
end;

procedure TForm1.btnDisplayNumClick(Sender: TObject);
var
 iCountB : Integer;
begin
 FOR iCountB := 1 to 10 do
 begin
  redOutput.Lines.Add(IntToStr(arrNum[iCountB]));
 end;
end;
end.


Take note:
• The array is declared globally so it can be used in more than one procedure.
• The counter used for the FOR loop is also used as index for the array.
• Another loop is used to display the values found in the array.
 

Data can also be entered into a globally declared array using an edit box and button (data is then displayed in a ListBox), for example:

var
 Form1: TForm1;
 arrNames : array[1..10] of String;
 iCount : integer; {Counts entered items}

implementation

{$R *.DFM}

procedure TForm1.btnEnterNameClick(Sender: TObject);
begin
 iCount := iCount + 1; {Increases counter}
 arrNames[iCount] := edit1.text;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
 iCount := 0; {Initial value of counter}
end;

procedure TForm1.btnDisplayNamesClick(Sender: TObject);
var
 iForCounter : integer; {FOR loop counter}
begin
 FOR iForCounter := 1 to iCount do
 begin
  lstNames.Items.Add(arrNames[iForCounter]);
 end;
end;

end.

Statistics
Members: 2
News: 41
Web Links: 4
Visitors: 447939