Arrays in C++: Initialization and Access Techniques

Written by

studymite

In the preceding chapter, we learned about arrays and how can we declare an array in C++. Now, we are going to focus more on arrays, as they are an important concept in C++ programming language.

Initializing Arrays:

You can initialize C++ array elements either one by one or using a single statement as follows −

int arr[5] = {100, 2, 3, 17, 50};

The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]. That is if you have declared an array of size 5 as in the above example then we can only store 5 elements in the array.

If you omit the size of the array, then an array will be created that will be large enough to hold the number of elements specified in the initialization statement.

int arr[5] = {100, 2, 3, 17, 50};

Here, an array with a size 5 will be created.

Accessing Array Elements:

We can access individual elements of an array, using any of the looping statements that we have studied so far.

Example

#include <iostream>

int main()
{
    int n[5] = {1, 2, 3, 4, 5}; // Declaring an array

    for (int i = 0; i < 5; ++i) // Loop to access array elements
    {
        std::cout << n[i] << std::endl; // Accessing individual elements of array, n.
    }

    return 0;
}

The above code when executed prints the following on the output screen.

Output

1

2

3

4

5

The above code accesses all the array elements one by one. Here, the for loop is used to access all the array elements and the loop counter variable, i, is used as an array index.

The possible values of i are as follows: 0,1,2,3,4, Thus, it accesses the array elements stored at these indexes.

Similarly, all the array elements can be accessed starting from 0 to array_size – 1.

Arrays in C++: Initialization and Access Techniques