Chapter 9
Arrays
Sometimes, programs must store large amounts of data in memory. Say you
want to store fifty different numbers in memory. You can define fifty different
variables. This would be very impractical. To solve this problem we must
use arrays. An array is a variable that is capable of holding several different
values. Each value in the array has a number.
Program Intro_to_Arrays (input, output);
var
Sample_Array : array [1..20] of integer;
i : integer;
Begin
For i := 1 to 20 do Begin
{assign i * 5 to each element of the array}
Sample_Array[i] := i * 5;
End;
{now print the contents of each element}
For i := 1 to 20 do Begin
Writeln(Sample_Array[i];
End;
End.
Sample_Array : array [1..20] of integer;
Declaring Arrays
Arrays must be declared in the Var section. It starts with the variable
name which must be a valid identifier like any other variable. It is followed
by a colon. After the colon comes the "ARRAY" keyword. The range
of the array must be included after the "ARRAY' keyword. In this case
the range of the array is from 1 to 20. The last two elements of the declaration
are the "OF" keyword and the array's datatype.
Using Arrays
Array elements are used very similarly to regular variables. The only
difference is that array elements must include the element's index number.
The index number can be an immediate value like in the following example:
Sample_Array[1] := 10;
Or it can be a variable.
x := 10;
Sample_Array[x] := 10;
If the index value is out of the array's range the program will return
an error message.
 |