Professional Documents
Culture Documents
Arrays
Arrays
Array is defined as a finite, ordered set of variables of the same type referenced under a
common name. In programming, we usually use array when the problem requires storage of
same items.
Points to remember
the variables in an array are called its components or elements
a specific element in an array is accessed by an index or subscript
all arrays consist of contiguous memory locations
the lowest address corresponds to the first element, the highest address corresponds to
the last element
arrays may have from one to several dimensions
In C, arrays must be explicitly declared so that the compiler can allocate space for them
in memory
Note that in C, there are no bounds checking on arrays. This means that you could
overwrite either end of the array and write into some other variable’s data, or even into
a piece of the program’s code.
Let’s look for example an implementation for a population for each of the 16 regions of
the Philippines. In C, we declare this as:
population
values
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
indices
The array when declared, starts its first element at a base address (B). Also note that in
C Language, every array starts its index at 0.
population
population
100
Each element in the array consumes byte(s) depending on the data type used.
Commonly used data types with their equivalent size
So, if the base address of the array population is 100, the address of its second element is
______. The address of the 5th element? ______ Address of population [9]? ______
population [15]? _______
float x[50];
base address = 1500
In C, lower bound is always zero (0). Therefore, the new formula would be
Example:
float x [50];
base address = 1500
Exercise:
Let’s look at another example. Let’s say we would like to track down the total quarterly
sales of each of the 5 salesmen. We declare this in C as
row
column
Salesmen
#1 #2 #3 #4 #5
0 1 2 3 4
1st 0 0,0 0,1 0,2 0,3 0,4
Quarter
Salesmen
#1 #2 #3 #4 #5
0 1 2 3 4
0 1000
Quarter
1
2
3
Though it is fairly easy to compute for the location of a particular element in a two-
dimensional array, it is not always the case. In some instances, the size of the array is so big that
tracking down the address of a particular element would be very hard if done manually. Just like
a single dimensional array, we could formulate a shorter way of doing it.
Hint: you’ll need the range (size) of the column, the row and column index in your formula
Here’s the formula for solving the address of a two-dim array’s element:
Example:
float sales[4][5];
Base address = 2000