Skip to content

Arrays

An array is a collection of elements of the same data type stored in contiguous memory locations. Each element in an array is accessed by an index. Arrays are used to store multiple values of the same data type under a single name.

Declaring Arrays

To declare an array in C++, you need to specify the data type of the elements and the size of the array. Here is the syntax of declaring an array:

data_type array_name[array_size];

Here is an example of declaring an array of integers with a size of 5:

int numbers[5];

You can also initialize the elements of an array when you declare it. Here is the syntax of initializing an array:

data_type array_name[array_size] = {value1, value2, value3, ..., valueN};

Here is an example of declaring and initializing an array of integers with a size of 5:

int numbers[5] = {10, 20, 30, 40, 50};

Accessing Elements of an Array

You can access the elements of an array using the index of the element. The index of the first element in an array is 0, and the index of the last element is the size of the array minus one. Here is an example of accessing the elements of an array:

int numbers[5] = {10, 20, 30, 40, 50};
cout << numbers[0]; // Output: 10
cout << numbers[1]; // Output: 20
cout << numbers[2]; // Output: 30
cout << numbers[3]; // Output: 40
cout << numbers[4]; // Output: 50

Iterating Through an Array

You can use loops to iterate through the elements of an array. Here is an example of using a for loop to iterate through the elements of an array:

int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
cout << numbers[i] << endl;
}

and the output will be:

Terminal window
10
20
30
40
50

Multidimensional Arrays

A multidimensional array is an array of arrays. You can create a two-dimensional array by specifying the number of rows and columns. Here is the syntax of declaring a two-dimensional array:

data_type array_name[rows][columns];

Here is an example of declaring a two-dimensional array of integers with 2 rows and 3 columns:

int matrix[2][3];

You can also initialize the elements of a two-dimensional array when you declare it. Here is an example of declaring and initializing a two-dimensional array of integers with 2 rows and 3 columns:

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

You can access the elements of a two-dimensional array using two indices. Here is an example of accessing the elements of a two-dimensional array:

int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
cout << matrix[0][0]; // Output: 1
cout << matrix[0][1]; // Output: 2
cout << matrix[0][2]; // Output: 3
cout << matrix[1][0]; // Output: 4
cout << matrix[1][1]; // Output: 5
cout << matrix[1][2]; // Output: 6