Web Tutor

Other Entries


Arrays in C++

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.
That means that, for example five values of type int can be declared as an array without having to declare five different variables(each with it's own identifier). Instead, using an array, the five int values are stord in contiguous memory locations, and all five can be accessed using the same identifier, with the proper index.
For example, an array containing 5 values of type int called values could be written as follows:


where each blank panel represents an element of array. In this case, these are values of type int. These elements are numbered from 1 to 5, with 1 being the first element and 5 being the last element. In C++, the first element in an array is indexed at zero and not one. 
Like a regular variable, an array must be declared before it is used. The following is the syntax of an array declaration in C++
type name [elements];

where type is a valid type(such as int, float), the name is a valid identifier and the element field which is always enclosed in square brackets([]) specifies the length of an array in terms of the number of elements.

Therefore the value array with 5 elements of type int can be written as follows:

int value [5];

 Note that the element field with square brackets representing the number of elements in the array must be a constant expression since arrays are blocks of memory whose size must be determined at compile time, before the program runs.


Initializing Arrays

By default, regular arrays of local scope(for example, those declared within a function) are left uninitialized. This means that none of its elements are set to any particular value; their contents are undetermined at the point the array is declared.

But the elements in the array can be explicitly initialized to specific values when it is declared, by enclosing those initial values in braces {}. For example

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

The number of values between braces {} shall not be greater than the number of elements in the array. 

Arrays can also be created without elements and that the elements can be added later. The code below create an array of 5 length but without element. This is called an empty array:

int val [5] = { };

Accessing the values of an Array

The values of any element in the array can be accessed just like the value of a regular variable of the same type. Below is the syntax for that:


Following the previous example in which value had 5 elements and each of those element was of type int, we can refer to each of the elements as follows:


For example: value[0] stores integer 1.


Posted in C++ on November 08 2022 at 04:44 PM

Comments (0)

No login