Introduction to Arrays in C++

Welcome to the thrilling world of C++ data structures, with a focus on Arrays! Arrays, which are collections of similar items housed in contiguous memory spots, are crucial tools often used for efficient storage and manipulation of data in C++.

Our objective is simple: we aim to understand what arrays are, and learn how to declare, initialize, access, modify, and traverse them in C++.

Understanding Arrays

An array in C++, named for a group of similar items, is akin to a row of post-office boxes. Each slot, known as an 'index', holds an item of the array's type. This characteristic makes arrays remarkably useful when we need to operate on multiple entities of the same type.

Arrays can be declared in several ways. Let's consider an array to hold the test scores of five students:

int scores[5]; // Array declaration without initialization
int scores[5] = {89, 94, 79, 86, 92}; // Array declaration and initialization with scores
int scores[] = {89, 94, 79, 86, 92}; // Compiler deduces size (5) based on the initializer list

int is the type of the array, denoting that it will store integer elements. The array, named scores, can hold five integer values, with one value for each student represented by a slot. The array requires a predefined size, it can't change its size dynamically.

Common Mistake

Note that you can't define an array like this:

int N;
std::cin >> N;
int array[N]; 

It won't work, as when the program starts, all variables are initialized, and only then the code executes. So, N will not hold the user's value when the array is initialized. The array in this code snippet can be of any size, most likely 0.

The only proper way is:

int max_N = 10000; // an example of the maximum possible N that the user will enter
int array[max_N];

In this case, we initialize the array with the maximum possible N, and then use only a part of this array when the program executes.

Accessing Array Elements

We can access elements within an array using their index, with 0 denoting the first element. For example, to print the score of the third student, the syntax is:

std::cout << scores[2] << "\n"; // Access and print the third element via index `2`

In C++, since valid array indices start from 0, always ensure that the index is within the bounds of the array. Indexes out of bounds can result in unpredictable behavior because C++ doesn't perform bounds checking!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal