Topic 4 Array
Topic 4 Array
OBJECTIVES
◦ Demonstrate the use of arrays
◦ Design program using the concept of pointer
◦ Describe the relationship between pointer and array.
What do you see ?
Consist of contiguous group of memory locations that all have the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1],
and ..., numbers[99] to represent individual variables
Explanation
Number[ 2 ] 18 Value
Name of an individual array Number[ 3 ] 10
element
Number[ 4 ] 23
int value = 7;
An array can be initialized by a list of initial values for array elements and they are separated
with commas and enclosed within braces. For example:
3 7 12 24 45 3 7 12 24 45
3 7 0 0 0 0 0 …. 0 0
3 7 12 24 45 3 7 12 24 45
3 7 0 0 0 0 0 …. 0 0
arrayname[index]
For example: an array called billy had 5 elements and each of those elements was of type int, the name which we can
use to refer to each element is the following:
For example :
To store the value 65 in the fourth element of billy ?
billy[3] = 65;
ONE DIMENSIONAL ARRAY
to pass the value of the third element of billy to a variable called a, we could write:
a = billy[2];
Notice that the third element of billy is specified billy[2], since the first
one is billy[0], the second one is billy[1], and therefore, the third one is
billy[2]. By this same reason, its last element is billy[4].
At this point it is important to be able to clearly distinguish between the two uses that
brackets [ ] have related to arrays.
A two-dimensional array has two subscripts; a three-dimensional array has three subscripts and so on.
int val = a[2][3]; int threedim[5][10][4];
Arrays can have any number of dimensions. A typical declaration for multidimensional array is :
we call it a
multidimensional array
data_type arrayname[size1][size2]...[sizeN];
For example :
int billy [3][4];
A good example of a two-dimensional array is a chess
board.
One dimension represents the eight rows; the other
dimension represents the eight columns.
INITIALIZING TWO DIMENSIONAL
ARRAY
A two-dimensional array can also be initialize.
Multidimensioned arrays may be initialized by specifying bracketed values for each row.
int a[3][4] = {
};
Analysis:
The above statement will take 4th element from the 3rd row of the array.