Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

ARRAYS

Declare one-dimensional arrays; read data into arrays; print array values;
assign values to array locations; traversing arrays ( e.g. changing the value
of an array element); linear searching of arrays
SCENARIO
Imagine writing a program that accepts the age of EACH students in
your class. If you wanted to store this information in variables you may
give the variables names something like this:
Age_1, Age_2, Age_3, Age_4, Age_5, Age_6....... And so on

Until you have a variable for everyone in the class! (25 variables?)

This takes a lot of time and would be inefficient, especially if you had
to store hundreds of variables of the same type.
There is a simpler way to store this information. Instead of using a
variable for each age, you could use an
ARRAY.
WHAT IS AN ARRAY?

An array is a data structure (storage area) that holds many different values of
the same DATATYPE.
Notice that all ages of students in your class would be of the same data type
(integer.)
An array may be created as: integers, characters, strings, or real data-types.

An array has one name, but it uses several storage locations to store variables
of the same data type.
VISUAL CONCEPT OF AN ARRAY
If we were to visualise what an array would look like, it would
appear as something like this:

Array NAME
Array INDEX
ages 1 2 3 4 5 6 7
15 14 12 13 16 17 14
Array ELEMENTS
Run in some kind of sequential order

Data Values in the array


DECLARING ARRAYS
Just like other variables, an array must be declared before it can be used. The
proper syntax for declaring an array is as follows:

Array_name : array [lower_number .. upper_number] of data_type;


Eg.
Ages : array [ 1 .. 7 ] of integer;
INITIALISING ARRAYS
For counter_name = lower_index to Upper_index do

array_name [ counter_name] = 0

endfor

E.g.

For i = 1 to 5 do

ages [ i ] = 0

endfor
READING DATA INTO ARRAYS
To assign an element to a position in an array, the format would be as follows:

Array_name [array index] = element;

E.g.

To assign the age 15 to position 4 in my array called ages my code would look
like this:
Ages [ 4 ] = 15;
PRINTING FROM ARRAYS
For counter_name = lower_index to Upper_index do

print array_name [ counter_name]

endfor

E.g.

For i := 1 to 5 do

print ages [ i ]

endfor
SEARCHING FOR VALUES IN ARRAYS
I want to print the word “yes” if any value in my array is equal to 13; otherwise print “no”
For counter_name = lower_index to Upper_index do
If array_name [ counter_name] = 13 then
Print “yes”
else
print “no”
endif
endfor

E.g.
For i := 1 to 5 do
if ages [ i ] = 13 then
print “yes”
else
print “no”
endfor

You might also like