C++ Arrays with Detailed Explanation and Examples

In this tutorial we will study and understand the concept of Arrays in C++ Programming.

An array is a series of elements of the same type placed in contiguous(one besides other) memory locations that can be individually referenced by adding an index to a unique identifier.
Consider a situation where you have to store age values for 100 people. In such situations creating 100 different variables will be tedious and inefficient. Instead, you can create one integer type array of size 100 to store these 100 different age values.  Syntax for creating a integer array variable named age of size 100:

All arrays are stored in contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Array Diagram


Arrays in C++ Programming

Declaring Arrays

To declare an array in C++, we specify the datatype of the elements and the number of elements required by an array as follows:

This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 5-element array called Arr of type double, use this statement:

Initializing Arrays

You can initialize C++ array elements at once using a single statement as follows:

The number of values between braces { } can not be larger than the total number of elements i.e size of the array (size mentioned inside the ‘[]’ brackets).

You can initialize single elements of the array as follows:

The above statement assigns element number 5th in the array a value of 200.0.
Array index values start from 0, therefore the 1st element in the array can be accessed by index 0. Thus the maximum index value of the array will always be one less than the actual size of the Array.

Accessing Array Elements


To access all values of the array, a loop can be used to iterate through the array values using the array index.

Arrays in C++ Example Program

Run Online

Watch it on YouTube

Leave a Reply
