Ch-3 Array
Ch-3 Array
ARRAYS
Arrays
• An array consists of a set of objects (called its elements), all of which
are of the same type and are arranged contiguously in memory.
• In general, only the array itself has a symbolic name, not its elements.
• Each element is identified by an index which denotes the position of
the element in the array.
• The number of elements in an array is called its dimension. The
dimension of an array is fixed and predetermined; it cannot be
changed during program execution.
• Arrays are suitable for representing composite data which consist of
many similar, individual items.
• E.g. a list of names, a table of world cities, etc…
Array [cont.…]
• An array variable is defined by specifying its dimension and the type
of its elements.
• For example, an array representing 10 height measurements (each
being an integer quantity) may be defined as:
• int heights[10];
• The individual elements of the array are accessed by indexing the
array. The first array element always has the index 0.
• Therefore, heights[0] and heights[9] denote, respectively, the first and
last element of heights.
• Each of heights elements can be treated as an integer variable. So, for
example, to set the third element to 177, we may write:
• heights[2] = 177;
• Attempting to access a non-existent array element (e.g., heights[-1] or
heights[10]) leads to a serious runtime error (called ‘index out of
bounds’ error).
Array Elements
• The items in an array are called elements (in contrast to the items in a
structure, which are called members).
• As we noted, all the elements in an array are of the same type; only
the values vary.
• Next figure shows the elements of the array age. (In the figure type
int is assumed to occupy two bytes, as in 16-bit systems.)
Basic operation
• Initializing Arrays
• By listing
• By loop
• Accessing Array Elements
• cout << “\nYou entered ” << age[j];
• A C++ string is simply an array of characters.
For example,
char str[] = "HELLO";
• defines str to be an array of six characters: five letters and a null character.
The terminating null character is inserted by the compiler.
• By contrast,
char str[] = {'H', 'E', 'L', 'L', 'O'};
• defines str to be an array of five characters.
Multidimensional Arrays
• An array may have more than one dimension (i.e., two, three, or
higher).
• The organization of the array in memory is still the same (a contiguous
sequence of elements), but the programmer’s perceived organization
of the elements is different.
• For example, suppose we wish to represent the average seasonal
temperature for three major Australian capital cities
• This may be represented by a two-dimensional array of integers:
Spring Summer Autumn Winter
int seasonTemp[3][4]; Sydney 26 34 22 17
Melbourne 24 32 19 13
Brisbane 28 38 25 20
CONT….