0% found this document useful (0 votes)
28 views9 pages

ARRAYS IN C++

The document provides an overview of arrays in C++, explaining their structure, declaration, initialization, and access methods. It covers one-dimensional and two-dimensional arrays, including syntax examples and the importance of using loops for efficient data handling. Additionally, it includes practice questions to reinforce understanding of array concepts.

Uploaded by

gamunorwataku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views9 pages

ARRAYS IN C++

The document provides an overview of arrays in C++, explaining their structure, declaration, initialization, and access methods. It covers one-dimensional and two-dimensional arrays, including syntax examples and the importance of using loops for efficient data handling. Additionally, it includes practice questions to reinforce understanding of array concepts.

Uploaded by

gamunorwataku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Arrays in C++ 2020

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.

[email protected], [email protected] Page 1


Arrays in C++ 2020

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);

[email protected], [email protected] Page 2


Arrays in C++ 2020

Example
int foo [5] = { 16, 2, 77, 40, 12071 };

This statement declares an array that can be represented like this:

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.

Accessing Array Elements


An array element is accessed by writing the identifier/name of the array followed by the
subscript/index/position number of the particular element in square brackets. Array elements are
counted from 0 and not 1. The first elements will always have position and index 0 and the last
element will have index number (position) N-1 if the array has N elements.

[email protected], [email protected] Page 3


Arrays in C++ 2020

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]

For if you declare your array as


int numArray[5];
the statement numArray[2] = 16; will store the value 75 in the third element of numArray.

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.

b) numArray[2] = 75; // access to an element of the array. (The number is square


brackets is position of a specific element of the array)

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.

[email protected], [email protected] Page 4


Arrays in C++ 2020

Consider the following examples:


Example 1
int nums[5], sum;
cout<<”Enter first element\n”;
cin>>nums[0];
cout<<”Enter second element\n”;
cin>>nums[1];
cout<<”Enter third element\n”;
cin>>nums[2];
cout<<”Enter fourth element\n”;
cin>>nums[3];
cout<<”Enter fifth element\n”;
cin>>nums[4];
sum = nums[0] + nums[1] + nums[2] + nums[3] + nums[4];
cout<<”The sum of the five array elements is “<<sum;
This program segment creates an integer array called nums which will store five (5) integers
entered by the user from the keyboard. The program segment will then calculate and display the
sum of the elements in the array. The problem with this is that there many lines of code (imagine
if there were 30 elements to be stored in the array. That means there would be 60 lines of code
just for input making the program unnecessarily too long). The code above can be made shorter
and simpler as shown in the example:
Example 2
int nums[5], x, sum = 0;
for(x = 0; x <= 5; x++)
{
cout<<”Enter element\n”;
cin>>nums[x];
sum += nums[x];
}
cout<<”The sum of the five array elements is “<<sum;

[email protected], [email protected] Page 5


Arrays in C++ 2020

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.

Multidimensional Arrays in C++

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.

Multidimensional arrays can be described as "arrays of arrays". For example, a bi-dimensional


array can be imagined as a bi-dimensional table made of elements, all of them of a same uniform
data type. Multidimensional arrays are not limited to two dimensions only. They can contain as
many dimensions as needed. Although be careful: the amount of memory needed for an array
increases exponentially with each dimension.

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

dataType arrayName [ numRows ][numCols ];

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.

[email protected], [email protected] Page 6


Arrays in C++ 2020

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.

Initializing Two-Dimensional Arrays

Multidimensional arrays may be initialized by specifying bracketed values for each row. For
example, the array grid declared above can be initialized as follows.

int grid[3][4] = {{0, 5,8,3},{5,4,0,2},{0,1,2,4}};

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:

int grid[3][4]={ 0, 5,8,3,5,4,0,2,0,1,2,4};

Accessing Two-Dimensional Array Elements


An element in 2-dimensional array is accessed by using the array name followed by the
subscripts i.e. row index and column index of the array. Each element in a two dimensional array

[email protected], [email protected] Page 7


Arrays in C++ 2020

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.

[email protected], [email protected] Page 8


Arrays in C++ 2020

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

[email protected], [email protected] Page 9

You might also like