Arrays hold lists of variables of the same data type. When there are large lists of variables and data, it is easier to contain the data in an array than have large amounts of separate variables to hold the data. Think of an array as a placeholder for piece of data.
The syntax of the array is:
Name_Of_Array : array[range] of datatype;
For example if we wanted to create an array that will hold five human first names the syntax will look like this:
FirstName : array[1..5] of string;
This is a sample program that creates an array for five human names, the names are hard coded into the program, and the program prints the names to the screen.
program Project1;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes
{ you can add units after this };
var
FirstName: array[1..5] of string;
x:integer;
begin
FirstName[1] := 'Joe';
FirstName[2] := 'Jim';
FirstName[3] := 'Jill';
FirstName[4] := 'Joan';
FirstName[5] := 'Jan';
for x:= 1 to 5 do
begin
writeln(FirstName[x]);
end;
writeln;
writeln;
writeln('Press <Enter> To Quit');
readln();
end.
This next program has an array that holds 6 integers. The program then calculates the sum of the integers and writes the sum to the screen.
program Project1;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes
{ you can add units after this };
var
nums: array[1..6] of integer;
x:integer;
sum:integer;
begin
nums[1] := 5;
nums[2] := 4;
nums[3] := 9;
nums[4] := -1;
nums[5] := 2;
nums[6] := 15;
sum := 0;
for x := 1 to 6 do
begin
sum := sum + nums[x];
end;
writeln('The Sum Of The Array Is: ', sum);
writeln;
writeln;
writeln('Press <Enter> To Quit');
readln();
end.
This final program asks the user for integers. After the user enters in the integers the program will add the numbers together and display the sum.
program Project1;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes
{ you can add units after this };
var
nums: array[1..6] of integer;
x:integer;
sum:integer;
begin
sum := 0;
for x := 1 to 6 do
begin
write('Enter Integer: ');
readln(nums[x]);
end;
for x := 1 to 6 do
begin
sum := sum + nums[x];
end;
writeln('The Sum Of The Array Is: ', sum);
writeln;
writeln;
writeln('Press <Enter> To Quit');
readln();
end.
Video Tutorial: Free Pascal Tutorial 9 - Arrays - Lazarus (8:32)
