C++ Arrays

In C++, an array is a collection of elements of the same data type, stored in contiguous memory locations. Arrays provide a convenient way to store and access multiple values of the same type. They are widely used in programming to store and manipulate collections of data efficiently.

Declaring an array in C++ involves specifying the data type of the elements and the number of elements in the array. The syntax for declaring an array is as follows:

datatype arrayName[arraySize];

Let’s take a look at an example to understand arrays better:

// Declaring an array of integers
int numbers[5];

// Assigning values to the array elements
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

In the above example, we have declared an array called “numbers” with a size of 5. We then assigned values to each element of the array using the index notation. The index starts from 0, so the first element is numbers[0], the second element is numbers[1], and so on.

Arrays can also be initialized at the time of declaration:

// Initializing an array of integers
int numbers[] = {10, 20, 30, 40, 50};

In this case, the size of the array is determined by the number of elements specified within the curly braces. The compiler automatically calculates the size of the array based on the number of elements provided.

Accessing elements of an array is done using the index notation. For example, to access the second element of the “numbers” array, you would use:

int secondNumber = numbers[1]; // Assigns the value 20 to secondNumber

It’s important to note that array indices start from 0 and end at size-1. Accessing an element outside the valid index range will result in undefined behavior or a runtime error.

C++ provides several ways to iterate over the elements of an array. One common approach is to use a for loop:

// Printing all the elements of the "numbers" array
for (int i = 0; i < 5; i++) {
    cout << numbers[i] << " ";
}

This loop iterates over each element of the array using the index variable “i” and prints its value. The loop condition “i < 5” ensures that the loop runs for all valid indices of the array.

Arrays can also be used to store elements of other data types, such as characters, floats, or custom objects. The process of declaring, initializing, and accessing elements remains the same, with the only difference being the data type specified.

In conclusion, arrays are a fundamental data structure in C++ that allow for the efficient storage and manipulation of multiple values of the same type. Understanding how to declare, initialize, and access elements of an array is crucial for building complex programs that require the handling of collections of data.

Scroll to Top