ARRAYS IN C++
ARRAYS IN C++
ARRAYS IN C++
An array is a collection of elements of the same type placed in contiguous memory locations that
can be individually referenced by using an index to a unique identifier.
More realistic programs need to store and process a substantial number of items of data. The data
types of variable discussed so far have been simple data types capable of holding a single value.
Arrays are a consecutive group of variables (memory locations) that all have the same data type
and share a common name. In many applications, arrays are used to represent vectors and
matrices.
An array is a data structure which allows a collective name to be given to a group of elements
which all have the same data type. An individual element of an array is identified by its own
unique index (or subscript).
An array can be thought of as a collection of numbered boxes each containing one data item. The
number associated with the box is the index of the item. To access a particular item the index of
the box associated with the item is used to access the appropriate box. The index must be an
integer and indicates the position of the element in the array. Thus the elements of an array are
ordered by the index.
Five values of type int can be declared as an array without having to declare five different
variables (each with its own identifier).
For example, a five element integer array foo may be logically represented as;
where each box represents an element of the array. In this case, these are values of type int.
These elements are numbered from 0 to 4, with 0 being the first while 4 being the last; In C++,
the index of the first array element is always zero. As expected, an n array must be declared prior
its use.
Declaration
An array declaration is very similar to a variable declaration. First a type is given for the
elements of the array, then an identifier for the array and, within square brackets, the number of
elements in the array. The number of elements must be an integer.
An array is declared by writing the data type of the array elements, followed by the array name
(which is any user defined identifier for the array) and size (maximum number of elements in the
array) enclosed in square brackets.
NOTE: Rules of naming identifiers should be followed when naming array names.
Syntax
dataType arrayName[size];
where dataType is any valid type (such as int, float ...), arrayName is any valid identifier and the
size field (which is always enclosed in square brackets []), specifies the maximum number of
elements that the array can hold.
Example
int numArray[5];
In the example above, the compiler will reserve space in memory enough to hold five (5)
elements which are all integers. All the five elements will be identified by the compiler using one
name (numArray).
Initializing an array
By default, arrays are uninitialized. This means that when you declare an array, the compiler will
simply reserve space for the array but there will be nothing stored in the array; i.e. their contents
are undetermined at the point the array is declared
Just like any ordinary variable, array variables can be initialized (given starting values) during
declaration. To initialize an array, you need to append an assignment operator and in curly
brackets (braces) the values that you want to put in the array as initial values.
Syntax
dataType arrayName(size) = {element1, element2, element3, …, elementN);
Example
int foo [5] = { 16, 2, 77, 40, 12071 };
The number of values between braces {} shall not be greater than the number of elements in the
array. For example, in the example above, foo was declared having 5 elements (as specified by
the number enclosed in square brackets, []), and the braces {} contained exactly 5 values, one for
each element. If declared with less, the remaining elements are set to their default values (which
for fundamental types, means they are filled with zeroes).
For example:
int bar [5] = { 10, 20, 30 };
Will create an array like this:
When an initialization of values is provided for an array, C++ allows the possibility of leaving
the square brackets empty[]. In this case, the compiler will assume automatically a size for the
array that matches the number of values included between the braces {}:
int foo [ ] = { 16, 2, 77, 40, 12071 };
After this declaration, array foo would be five int long, since we have provided five initialization
values.
The values of any of the elements in an array can be accessed just like the value of a regular
variable of the same type.
Syntax
arrayName[index]
In C++, it is syntactically correct to exceed the valid range of indices for an array. This can
create problems, since accessing out-of-range elements do not cause errors on compilation, but
can cause errors on runtime. The reason for this being allowed is because index checking slows
down program execution.
NOTE: It is important to be able to clearly distinguish between the two uses that brackets [ ]
have related to arrays. They perform two different tasks: one is to specify the size of arrays
when they are declared; and the second one is to specify indices for concrete array elements
when they are accessed. Do not confuse these two possible uses of brackets [] with arrays.
Example
a) int numArray[5]; // declaration of a new array (The number in square brackets is
the maximum number of elements the array can hold.
The main difference is that the declaration is preceded by the type of the elements, while the
access is not.
NOTE: The best way to access array elements if you want to access all elements is to use a
loop.
The two examples above perform the same task but the second example is simpler and shorter
than the first and that’s because the second one uses a loop. Regardless of the number of
elements to be stored in the array, the number of statements does not change. Note an additional
variable declared in the second example which is the loop variable and will be used to keep track
of the array index for each iteration of the loop. Note also the initialization of the variable sum to
zero (0) in the second example because sum in the second example is cumulative.
The arrays that we have looked at so far are all one-dimensional arrays, i.e. they all had one row
and several columns. However, C++ allows multidimensional arrays.
Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. A two dimensional array can
be thought as a table which will have x number of rows and y number of columns.
To declare a two-dimensional you use the same method as used when declaring a one
dimensional array, but for the two dimensional array you put two sets of square brackets, the first
set showing the number of rows and the second set showing the maximum number of columns:
Syntax
Where dataType can be any valid C++ data type and arrayName will be a valid C++ identifier
for the array, numRows is the maximum number of rows that the array can hold and numCols is
the maximum number of columns that the array can hold.
For example, a 2-dimentional array grid which contains three rows and four columns can be
shown as below:
int grid[3][4];
0 1 2 3
0
grid 1
2
Thus, every element in array grid is identified in the following way grid[ i ][ j ], where grid is
the name of the array, and i is the row index/subscript and j is the column index/subscript that
uniquely identify each element in grid.
Multidimensional arrays may be initialized by specifying bracketed values for each row. For
example, the array grid declared above can be initialized as follows.
i.e.
int grid[3][4]={
{0,5,8,3},/* initializers for row indexed by 0 */
{5,4,0,2},/* initializers for row indexed by 1 */
{0,1,2,4}/* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:
always has two indexes, row index first which states the row in which the specific element is
located and then the column index which states the column in which the element is located.
Syntax
arrayName[rowIndex][columnIndex]
for example
As already indicated, the best way to access array elements if you want to access all elements is
to use a loop. For a two-dimensional array, you will have to use two loops (the loop for the rows
and the loop for the columns). The two loops will however need to be nested. The loop for the
columns will be nested inside the loop for the rows.
Example
int grid[3][3], rowIndex, colIndex;
for(rowIndex = 0; rowIndex < 3; rowIndex++)
{
for(colIndex = 0; colIndex < 3; colIndex++)
{
cout<<”Enter array element “;
cin>>grid[rowIndex][colIndex];
}
}
The code snippet above creates a two array called grid with three rows and three columns. Then
using the nested loops the code snippet requests the user to enter numbers from the keyboard and
store the numbers in the array. Two dimensional arrays are used to manipulate matrices in
programming.
Practice Questions
1. Write a C++ program that creates and loads an array of 15 floating point values. Your
program should calculate and display the average of the values in the array. Also display
the array elements starting with the last one.
2. Write a C++ program that creates and loads an array of 20 integer elements. Your
program should then request the user to enter a number and it will then count and display
the number of times that number is found in the array.
3. Write a C++ program that creates and loads a 3 x 3 array of integers. Your program
should display the array and its transpose in matrix form.a