An Array is a powerful data structure that stores variable data having the same data type. It is just like a small fixed number of boxes linked together one after the other storing things that are related to each other. An array is said to be a static data structure because, once declared, its original size that is specified by the programmer will remain the same throughout the whole program and cannot be changed.
Up until now, we have used single variables only as a tool to store data. Now we will be using the array data structure and here is how it is declared:
Var
myArray : Array[1..20] of Integer;
<arrayName> : Array[n..m] of <Data Type>;
An array data structure defines the size of the array and the data type that it will use for storing data. In the above example, the array stores up to 20 integers however I may have used 30 integers or more. This size depends on your program requirements.
Arrays are used just like ordinary variables. They are used to store typed data just like the ordinary variables. You will now learn how to assign data to arrays and read data from arrays.
In the example above, I have declared 20 integers and I should be able to access each and one of them and here is how I do it.
To assign values to a particular integer of an array, we do it like this:
myArray[5] := 10;
myArray[1] := 25;
<arrayName>[index] := <relevant data>
You just take the array in subject, specify the index of the variable of the array and assign it a value relevant to the data type of the array itself.
Reading a value from an array is done as follows:
Var
myVar : Integer;
myArray : Array[1..5] of Integer;
Begin
myArray[2] := 25;
myVar := myArray[2];
End. |
Just like ordinary variables, arrays should be initialised, otherwise scrap data will remain stored in them. If we want to intialise 2 whole 20-sized integer and boolean arrays to 0 and false respectively, we do it like this:
Var
i : Integer;
myIntArray : Array[1..20] of Integer;
myBoolArray : Array[1..20] of Boolean;
Begin
For i := 1 to 20 do
Begin
myIntArray[i] := 0;
myBoolArray[i] := false;
End;
End. |
 |