You are on page 1of 3

INTRODUCTION TO ARRAYS IN PROGRAMMING (PASCAL)

What is an array: basically it is a holding position in memory similar to that of a variable. The
difference is that it has compartments called elements. Each element has an index number starting
with 1.
Demo drawing looks like this

1 2 3 4 5 6 7

The name of the is written above the drawing to the left.


This array has seven elements.
Note: the contents of each element are of the same type. If you declare the array as of type integer,
then only integers can be placed in each element.
How do you declare an array: <array Name> : ARRAY[1..n] of <type> {Pascal}
To apply this to the above array
pseudocode: Marks : an array (1..7) of type integer
Pascal: Marks:array[1..7] of integer
In the following tasks each one will be written in pseudocode then in Pascal
1- To add data to a specific element (e.g. index 4)
Marks(4) ²65 Marks[4]:=65;
2- To Add to the value in a specific element {Add 38 to Marks[6]}
Marks(6)²Marks(6)+38 Marks[6]:=Marks[6]+38;

3- To subtract from the value in a specific element {subtract 38 from Marks[6]}


Marks(6)²Marks(6)-38 Marks[6]:=Marks[6]-38;
Note that No.s 2 & 3 are updates
4- To replace the value in one element with the value in another
Marks(2)²Marks(7) Marks[2]:=Marks[7];
{Read ‘replace the value in Marks[2] with the value in Marks[7]}
5- To update element 3 by 5%
Marks(3)²Marks(3)+Marks(3) x 0.05 Marks[3]:=Marks[3]+Marks[3] * 0.05;
Same pattern holds if you want to decrease the value; just change + to -
6- To allow the user to input values in a single element
Get Marks(2) Readln (Marks[2]);
7- To display the contents of a single element
Print Marks(7) Writeln (Marks[7]);
8- To allow the user to input data in all elements, you need a For / While loop
For index = 1 to 7 do For index = 1 to 7 do
Get Marks(index) Readln (Marks[index]);

index²1 index:=1;
While index <8 do While index <8 do
Get Marks(index) Readln (Marks[index]);
Index²index+1 Index²index+1;

9- To display the data in all elements, you need a For / While loop
For index = 1 to 7 do For index = 1 to 7 do
Pirnt Marks(index) Writeln (Marks[index]);

index²1 index:=1
While index <8 do While index <8 do
Print Marks(index) Writeln (Marks[index]);
Index²index+1 Index²index+1;

Note that the size of the loop is the same as the size of the array. This means that you can use a
constant which will allow you to change the size of the array without having to change anything else
in the code. Look at the below.
Here is the constant; call it n / LastNumber / ArraySize / something which makes sense.
10- To allow the user to input data in all elements, you need a For / While loop
Constant n ²7 Const n:=7;
For index = 1 to n do For index = 1 to n do
Get Marks(index) Readln (Marks[index]);

index²1 index:=1;
While index <n+1 do While index <n+1 do
Get Marks(index) Readln (Marks[index]);
Index²index+1 Index²index+1;

By simply change the value of n, the entire code is modified.

You might also like