Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C++

Learn step by step



Arrays

An array in C++ is similar to C language. It can be defined as a number of contiguous memory locations, each of which can store data of same type and which can be references through the same variable name.

An array is a collective name given to a group of similar type of quantities.

These similar type quantities could be percentage of 200 students, number of chairs in home, or salaries of 200 employees or ages of 100 students, etc. Therefore an array is a collection of similar data elements.

These similar data elements could be either all integers or all floats or all characters etc. Generally, the array of characters is called a "string"( or we can say 'string' is an array of character type), where as an array of integers or floats is called simply an array. All elements of a given array must be of the same data type i.e we can not have an array of 10 numbers, in which 5 are integer & 5 are floats.

Array Declaration and Usage

Suppose that we want to find the average of marks for a class of total 30 students, we certainly don't want to create 30 variables: mark1, mark2, ..., mark30. Instead, We could use a single variable, called an array, with size of 30.

An array is a list of elements of same type, identified by a pair of square brackets [ ]. To make use of an array, we need to declare the array with 3 things: name, type and dimension (or size / length).
Syntax:

type arrayName[arraylength];     // arraylength can be a literal or a variable

I recommend using a plural name for array, e.g., marks, rows, numbers.
For example

// Declare and initialize an int array of three elements
int numbers[3] = {11, 33, 44};
// If length is omitted, the compiler counts the elements
int numbers[] = {11, 33, 44};
// Number of elements in initialization shall be equal to or less than length
int numbers[5] = {11, 33, 44};         // Remaining elements are zero. Confusing! Don't do this
int numbers[2] = {11, 33, 44};         // ERROR: too many initializers

// Use {} or {0} to initialize all elements to 0
int numbers[5] = {0};         // First element to 0, rest also to zero
int numbers[5] = {};         // All element to 0 too

/* Test local array initialization (TestArrayInit.cpp) */
#include <iostream>
using namespace std;

int main() {
int const SIZE = 5;

int a1[SIZE];         // Uninitialized
for (int i = 0; i < SIZE; ++i) cout << a1[i] << " ";
cout << endl;         // ? ? ? ? ?

int a2[SIZE] = {21, 22, 23, 24, 25};         // All elements initialized
for (int i = 0; i < SIZE; ++i) cout << a2[i] << " ";
cout << endl;         // 21 22 23 24 25

int a3[] = {31, 32, 33, 34, 35};         // Size deduced from init values
int a3Size = sizeof(a3)/sizeof(int);
cout << "Size is " << a3Size << endl;         // 5
for (int i = 0; i < a3Size; ++i) cout << a3[i] << " ";
cout << endl;         // 31 32 33 34 35

int a4[SIZE] = {41, 42};         // Leading elements initialized, the rests to 0
for (int i = 0; i < SIZE; ++i) cout << a4[i] << " ";
cout << endl;         // 41 42 0 0 0

int a5[SIZE] = {0};         // First elements to 0, the rests to 0 too
for (int i = 0; i < SIZE; ++i) cout << a5[i] << " ";
cout << endl;         // 0 0 0 0 0

int a6[SIZE] = {};         // All elements to 0 too
for (int i = 0; i < SIZE; ++i) cout << a6[i] << " ";
cout << endl;         // 0 0 0 0 0
}

We can refer to element of an array by index (or subscript) enclosed within square bracket [ ]. Index of array begins with zero.
Example, suppose that marks is an int array of 5 elements, then 5 elements are: marks[0], marks[1], marks[2], marks[3], and marks[4].

// Declare & allocate a 5-element int array
int marks[5];
// Assign values to the elements
marks[0] = 95;
marks[1] = 85;
marks[2] = 77;
marks[3] = 69;
marks[4] = 66;
cout << marks[0] << endl;
cout << marks[3] + marks[4] << endl;

Fig 1.

To create an array, we need to known length (or size) of the array in advance. Once an array is created/initialized, its length is fixed and cannot be modified. At times, this is hard to ascertain length of an array (e.g., how many students in a class?). Nonetheless, we need to estimate the length and allocate an upper bound. This is obviously a major drawback of using an array. C++ also has a vector template class (and C++11 added an array template class), It supports dynamic resizable array.

We can find the array length using expression sizeof(arrayName)/sizeof(arrayName[0]), where sizeof(arrayName) returns the total bytes of the array and sizeof(arrayName[0]) returns the bytes of first element.

C/C++ doesn't perform array index-bound check. In other words we can say, if index is beyond the array's bounds, it doesn't issue a warning/error.
Example,

const int size = 5;
int numbers[size]; // index of array from 0 to 4

// Index out of bound!
// Can compiled and run, but could pose very serious side effect!
numbers[88] = 999;
cout << numbers[77] << endl;
Accessing the values of an array

Values of any element of an array can be accessed by its address/index.
The syntax is:

name[index]

foo had total 5 elements and each of those was of int type, the name that can be used to refer to each element is the following:
Following previous examples in which

Fig 2.

Example, the following statement stores the value 75 in the third element of foo:

foo [2] = 75;

and, Example, following copies the value of the third element of foo to a variable called x:

x = foo[2];

So, the expression foo[2], itself is a variable of int type.

int foo[5];         // declaration
foo[2] = 75;         // accessing value of the element of array

Don't confuse these 2 possible uses of brackets [ ] with arrays.

Main difference is declaration is preceded by the type of the elements, while the access is not.

Other valid operations with arrays:

foo[0] = a;
foo[a] = 75;
b = foo [a+2];
foo[foo[a]] = foo[2] + 5;

// arrays example
#include <iostream>
using namespace std;

int foo [] = {16, 2, 77, 40, 12071};
int n, result=0;

int main ()
{
for ( n=0 ; n<5 ; ++n )
{
result += foo[n];
}
cout << result;
return 0;
}

Output

12206
Multidimensional arrays

Multidimensional arrays can be described as "arrays of arrays". E.g., Bi-dimensional array can be imagined as a two-dimensional table made of elements, all of them are of a same uniform data type.

Example,

int[2][3] = { {1, 2, 3}, {4, 5, 6} };

Fig 3.

For 2D array, first index is row number, and second index is column number. Elements are stored in row-major manner, where column index runs out first.

Fig 4.

jimmy represents a bidimensional array of 3 per 5 elements of type int. C++ syntax for this is:

int jimmy [3][5];

For example, the way to reference second element vertically and fourth horizontally in an expression would be:

jimmy[1][3]

Fig 5.

Multidimensional arrays are not limited to 2 indices (i.e., 2-dimensions). They can contain as many indices as needed. Although be careful: because, the amount of memory needed for an array increases fastly with each dimension.
Example:

char century [100][365][24][60][60];

declares an array with an element of type char for each second in century. This amounts to more than 3 billion char! So, this would consume more than 3 gigabytes of memory!

At the end, multidimensional arrays are just an abstraction for programmers, since same results can be achieved with a simple array:

int jimmy [3][5];         // is equivalent to
int jimmy [15];         // (3 * 5 = 15)



Related Videos