How to Create and access an array in C++ ?


In C++, an array is a collection of elements of the same data type, stored in contiguous memory locations. Here are the steps to create and access an array in C++:

Creating an Array

To create an array in C++, you need to declare the array variable and specify the number of elements it will hold. The syntax for declaring an array is as follows:

data_type array_name[array_size];

Here, data_type is the data type of the elements in the array, array_name is the name of the array variable, and array_size is the number of elements the array will hold.

For example, to create an array of integers that can hold 5 elements, you can use the following code:

int my_array[5];

This will create an array named my_array that can hold 5 integers.

Accessing Array Elements

To access an element in an array, you need to use the array index. The index is a zero-based integer that specifies the position of the element in the array. The syntax for accessing an element in an array is as follows:

array_name[index];

Here, array_name is the name of the array variable, and index is the zero-based index of the element you want to access.

For example, to access the third element in the my_array array created above, you can use the following code:

int third_element = my_array[2];

This will assign the value of the third element in the my_array array to the third_element variable.

Initializing an Array

You can initialize an array at the time of declaration by providing a comma-separated list of values enclosed in curly braces. The number of values in the list should be equal to the size of the array. For example, to create an array of integers and initialize it with values, you can use the following code:

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

This will create an array named my_array that can hold 5 integers and initialize it with the values 1, 2, 3, 4, and 5.

Example

Here's an example program that demonstrates how to create and access an array in C++:

#include <iostream>

using namespace std;

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

    cout << "The third element in the array is: " << my_array[2] << endl;

    return 0;
}

This program creates an array of integers named my_array and initializes it with the values 1, 2, 3, 4, and 5. It then accesses the third element in the array using the index 2 and prints its value to the console. The output of this program will be:

The third element in the array is: 3


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.