Arrays in C++

Arrays are used to store a number of items of the same type in one single variable. They are usually placed in the same segment of memory with accessible elements for each. This tutorial will explain you the tricks to C++ arrays.

Array Declaration

To declare arrays in C++ you need to specify the type of the array elements, name of array variable and the number of elements required by an array.

type variableName [size];

Example

int foo[5];

Array Initialization

In C++ array elements can be initialized one by one or through a single statement.

int bar[12];
bar[0] = 8;
bar[3] = 2;

OR

int bar[12] = {8,1,3,2,9,7,4,0,5,11,12,6};

The number of values between braces {} can not exceed the size of array which was specified at the time of array declaration.

Accessing Array Elements

The value of any of the elements in an array can be accessed by indexing the array name. You can access the value of 5th element of bar[] array as follows.

count << bar[4];

Example

#include <iostream>
using namespace std;

int main () {

int bar[12] = {8,1,3,2,9,7,4,0,5,11,12,6}; // bar is an array of 12 integers

// output each element of array
for(int i = 0; i < 12; i++ ){

cout << bar[i] << “\n”;

}

return 1;

}

Multidimensional Arrays

Arrays of arrays are called multidimensional arrays. C++ allows multidimensional arrays.

Multidimensional array declaration

int foo[2][4];

Multidimensional Arrays Example

#include <iostream>
using namespace std;

int main () {

// an array with 5 rows and 2 columns.
int foo[5][2] = { {1,3}, {0,2}, {2,6}, {3,1},{9,1}};

// output each array element’s value
for ( int i = 0; i < 5; i++ ) {

for ( int j = 0; j < 2; j++ ) {

cout << “foo[” << i << “][” << j << “]: “;
cout << foo[i][j]<< endl;

}

}

return 0;

}

Output

foo[0][0]: 1
foo[0][1]: 3
foo[1][0]: 0
foo[1][1]: 2
foo[2][0]: 2
foo[2][1]: 6
foo[3][0]: 3
foo[3][1]: 1
foo[4][0]: 9
foo[4][1]: 1

Leave a Reply

Your email address will not be published. Required fields are marked *