Arrays in C++ Programming Language

In C ++ programming language, arrays are elements of the same type placed in adjacent memory locations. Items can be referenced individually by a unique identifier with an added index.

This allows you to declare multiple variable values ​​of a specific type and access them individually without having to declare a variable for each value. In this article, I will introduce you to tables in C ++ programming language.

Also, Read – The Fundamentals of C++ Programming Language.

Arrays in C ++: Initialization

An array is just a block of sequential memory locations for a specific type of variable. Arrays in the C ++ programming language are allocated in the same way as normal variables, but with brackets appended to its name [] which contain the number of elements that will fit in the array’s memory.

The following example array uses type int, variable name arrayOfInts, and the number of elements [5] for which the array has space:

int arrayOfInts[5];

An array can be declared and initialized at the same time like this:

int arrayOfInts[5] = {10, 20, 30, 40, 50};

When initializing an array listing all of its members, it is not necessary to include the number of elements in square brackets. It will be automatically calculated by the compiler. In the following example, it is 5:

int arrayOfInts[] = {10, 20, 30, 40, 50};

It is also possible to initialize only the first elements while allocating more space. In this case, the definition of the length in parentheses is mandatory. The following will allocate an array of length 5 with partial initialization, the compiler initializes all remaining elements with the standard value of the element type, in this case zero.

int arrayOfInts[5] = {10,20}; // means 10, 20, 0, 0, 0

Arrays of other basic data types can be initialized in the same way.

char arrayOfChars[5]; // declare the array and allocate the memory, don't initialize
char arrayOfChars[5] = { 'a', 'b', 'c', 'd', 'e' } ; //declare and initialize
double arrayOfDoubles[5] = {1.14159, 2.14159, 3.14159, 4.14159, 5.14159};
string arrayOfStrings[5] = { "C++", "is", "super", "duper", "great!"};

It’s also important to note that when accessing array elements, the index (or position) of the array element starts at 0.

int array[5] = { 10/*Element no.0*/, 20/*Element no.1*/, 30, 40, 50/*Element no.4*/};
std::cout << array[4]; //outputs 50
std::cout << array[0]; //outputs 10

I hope you liked this article on arrays in C ++ programming language. Please feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1498

Leave a Reply