In this tutorial, you will learn commonly used C++ array operations, including declaring and initializing arrays, accessing elements by index, finding the array length, traversing and printing elements, updating values, searching an array, and working with multidimensional arrays.

C++ Arrays and Array Operations

An array in C++ stores a fixed number of elements of the same data type. The elements are stored in contiguous memory locations and are accessed using an index.

For a built-in C++ array, the size is normally fixed when the array is created. For example, the following declaration creates an array that can store five integers.

</>
Copy
int numbers[5];

The main operations performed on an array include initialization, element access, traversal, updating values, searching, and processing elements. Operations such as insertion and deletion require extra handling with built-in arrays because their size does not automatically grow or shrink.

C++ Array Indexes Start at 0

C++ arrays use zero-based indexing. The first element is at index 0, the second element is at index 1, and so on. For an array containing n elements, the last valid index is n - 1.

</>
Copy
int numbers[] = {10, 20, 30, 40};

std::cout << numbers[0] << "\n";
std::cout << numbers[3] << "\n";
10
40

Accessing an element outside the valid index range causes undefined behavior. For example, index 4 is not valid for an array containing only four elements.

1. Initialize a C++ Array

To initialize a C++ array, write the array name followed by square brackets and assign a list of values enclosed in braces. When an initializer list is provided, C++ can determine the array size automatically.

</>
Copy
data_type array_name[] = {value1, value2, value3};

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   int arr1[] = {7, 3, 8, 7, 2};

   //print arrays
   for (int i=0; i < sizeof(arr1)/sizeof(*arr1); i++) {
      cout << arr1[i] << "  ";
   }
}

Output

7  3  8  7  2

In this example, the compiler determines that arr1 contains five elements from the five values in the initializer list.

Complete Tutorial – C++ Initialize Array

2. Find the Length of a C++ Array

The length of an array is the number of elements it contains. One way to count the elements is to traverse the array and increment a counter for each element.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   int arr[] = {3, 5, 8, 13, 21, 34};
   int len = 0;

   for (int n: arr)
      len++;

   cout << len;
}

Output

6

For a built-in array that is still available as an array in the current scope, its element count can also be calculated by dividing the total array size by the size of one element.

</>
Copy
sizeof(arr) / sizeof(arr[0])

In C++17 and later, std::size() provides another convenient way to obtain the number of elements in a built-in array when the array itself is available.

</>
Copy
#include <iostream>
#include <iterator>

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    std::cout << std::size(numbers);
    return 0;
}
5

The sizeof technique should not be used after a built-in array has decayed to a pointer, such as when it is passed to many ordinary function parameters. In that situation, pass the element count separately or use a container such as std::array or std::vector when appropriate.

Complete Tutorial – C++ Array Length

3. Print All Elements of a C++ Array

To print all elements of an array, traverse the array with a loop and print each element during the iteration. A range-based for loop is convenient when you need every element and do not need its index.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   int arr[7] = {25, 63, 74, 69, 81, 65, 68};
   
   for (int element: arr) {
      cout << element << "  ";
   }
}

Output

25  63  74  69  81  65  68

Complete Tutorial – C++ Print Array

4. Loop Through C++ Array Elements

Array traversal means visiting the elements one by one. You can traverse an array using a for loop, a while loop, or a range-based for loop. An index-based loop is useful when the position of each element is needed.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   int arr[7] = {25, 63, 74, 69, 81, 65, 68};
   
   int i=0;
   while (i < 7) {
      cout << arr[i] << "  ";
       i++;
   }
}

Output

25  63  74  69  81  65  68

Complete Tutorial – C++ Loop through Array Elements

5. Access and Update a C++ Array Element

Use the element’s index inside square brackets to read or change a value. Because indexes begin at zero, arr[1] refers to the second element.

</>
Copy
#include <iostream>

int main() {
    int arr[] = {10, 20, 30, 40};

    std::cout << "Before: " << arr[1] << "\n";

    arr[1] = 25;

    std::cout << "After: " << arr[1] << "\n";
    return 0;
}
Before: 20
After: 25

Updating an element replaces the value stored at that position; it does not change the number of elements in the array.

6. Search for a Value in a C++ Array

A simple way to search an unsorted array is linear search. Starting with the first element, compare each value with the target until a match is found or the end of the array is reached.

</>
Copy
#include <iostream>

int main() {
    int arr[] = {12, 35, 7, 48, 21};
    int target = 48;
    int length = sizeof(arr) / sizeof(arr[0]);
    int foundIndex = -1;

    for (int i = 0; i < length; i++) {
        if (arr[i] == target) {
            foundIndex = i;
            break;
        }
    }

    if (foundIndex != -1) {
        std::cout << "Found at index " << foundIndex;
    } else {
        std::cout << "Value not found";
    }

    return 0;
}
Found at index 3

7. Find the Sum of C++ Array Elements

Many array operations process every element to calculate a result. For example, to find the sum, initialize an accumulator to zero and add each array element to it.

</>
Copy
#include <iostream>

int main() {
    int arr[] = {4, 6, 8, 10};
    int sum = 0;

    for (int value : arr) {
        sum += value;
    }

    std::cout << "Sum = " << sum;
    return 0;
}
Sum = 28

8. Sort C++ Array Elements

The standard library function std::sort(), declared in <algorithm>, can sort the elements of a built-in array. Pass pointers to the beginning and one-past-the-end of the range to be sorted.

</>
Copy
#include <algorithm>
#include <iostream>

int main() {
    int arr[] = {9, 3, 7, 1, 5};
    int length = sizeof(arr) / sizeof(arr[0]);

    std::sort(arr, arr + length);

    for (int value : arr) {
        std::cout << value << " ";
    }

    return 0;
}
1 3 5 7 9 

Insertion and Deletion in Built-in C++ Arrays

A built-in C++ array has a fixed capacity. It does not provide member functions that automatically insert a new element and enlarge the array or erase an element and reduce its physical size.

To insert an item into a logical sequence stored in a built-in array, you normally keep track of how many positions are currently in use, ensure unused capacity is available, and shift elements to make room. Deletion similarly involves shifting later values and reducing the logical element count.

If the number of elements needs to grow and shrink dynamically, std::vector is often more suitable. If a fixed-size standard-library container is preferred, std::array provides an array-like container with useful member functions while retaining a fixed number of elements.

One-Dimensional and Multidimensional Arrays in C++

A one-dimensional array stores a single sequence of elements. A multidimensional array contains arrays as elements. A two-dimensional array is commonly used to represent data arranged in rows and columns.

</>
Copy
int oneDimensional[5];
int twoDimensional[2][3];

The following two-dimensional array has two rows and three columns.

</>
Copy
#include <iostream>

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

    for (int row = 0; row < 2; row++) {
        for (int column = 0; column < 3; column++) {
            std::cout << matrix[row][column] << " ";
        }
        std::cout << "\n";
    }

    return 0;
}
1 2 3
4 5 6

Built-in C++ Arrays Compared with std::array

C++ supports traditional built-in arrays as well as the standard-library std::array container. Both represent a fixed number of elements, but std::array provides member functions such as size(), begin(), end(), and at().

</>
Copy
#include <array>
#include <iostream>

int main() {
    std::array<int, 4> numbers = {10, 20, 30, 40};

    std::cout << "Length: " << numbers.size() << "\n";
    std::cout << "First: " << numbers[0] << "\n";

    return 0;
}
Length: 4
First: 10

C++ Array Operations Summary

In this C++ Tutorial, we covered the main operations performed on arrays: initialization, zero-based element access, finding the array length, printing and traversing elements, updating values, searching, calculating results, sorting, and working with multidimensional arrays. We also noted that built-in arrays have a fixed size and compared them briefly with std::array and dynamically sized containers such as std::vector.