Array in C++

An array is a group of data items with same data type that are stored in a row or column of memory.

For example, if we create an array to store 5 integer values, then each block will only keep the value of an integer data type. If we try to store a float value or anything other than an integer, we will get a compile-time error.

C++ array example

Here,
First Index = 0
Last Index = 4
Array Length = 5

Program to illustrate arrays in C++:


#include <iostream>
using namespace std;

int main()
{
    int arr[4] = {5, 10, 25, 32}; // initializing an array of size 4

    cout << "Data item at index 3 = " << arr[3] << "\n"; // gives the element at index 3
    cout << "Data item at index 2 = " << arr[2];         // gives the element at index 2

    return 0;
}
Output
Data item at index 3 = 32
Data item at index 3 = 25

Types of arrays in C++

There are two types of arrays in C++:

  • Single Dimensional Array - In this type of array, elements are stored in a single dimension. For example:
  • 
    #include <iostream>
    using namespace std;
    
    int main()
    {
            int array[5] = {7, 2, 6, 1, 5};
            for (int i = 0; i < 5; i++)
            {
                    cout << array[i] << " ";
            }
            return 0;
    }
    
    Output
    7 2 6 1 5
  • Multidimensional Array - Multidimensional Array can have any number of dimensions. Two-dimensional array also comes under this category of array. For example:
  • 
    #include <iostream>
    using namespace std;
    
    int main()
    {
            int array[3][3] = {{2, 4, 6}, {3, 6, 1}, {5, 7, 7}};
            for (int i = 0; i < 3; ++i)
            {
                    for (int j = 0; j < 3; ++j)
                    {
                            cout << array[i][j] << " ";
                    }
                    cout << "\n"; // newline every row
            }
            return 0;
            cout << endl;
            return 0;
    }
    
    Output
    2 4 6
    3 6 1
    5 7 7

Advantages of Arrays

Following are some advantages of using arrays in C++:

  • Accessing an element is very easy in an array by using the index number.
  • Arrays have low overhead.
  • Arrays store multiple data of the same types using a single name.