Arrays
Introduction to Arrays in C++
An array is a fundamental data structure in C++ that allows us to store multiple elements of the same data type in a single variable. It's like a collection of items (elements), where each item is located at a specific point (index). If you think of a variable as a mailbox, an array is like a post office with several mailboxes.
Declaration of Arrays
To declare an array in C++, we use the following syntax:
dataType arrayName[arraySize];
Here, dataType
can be any valid C++ data type, arrayName
is the name of the array, and arraySize
is an integer representing the number of elements the array can hold.
For example:
int numbers[5];
This declares an array named numbers
that can hold 5 integer values.
Initializing Arrays
We can initialize an array at the time of declaration. For example:
int numbers[5] = {1, 2, 3, 4, 5};
If we don't initialize the array at the time of declaration, the compiler will automatically initialize the array elements to zero (for numeric data types).
Accessing Array Elements
We can access an element in an array by referring to the index number. Arrays in C++ are zero-indexed, meaning the first element is at index 0, the second element is at index 1, and so on.
Here's how you can access the element at index 2 in the numbers
array:
int num = numbers[2];
Remember, trying to access an index outside of the array size (such as numbers[10]
for an array of size 5) will result in undefined behavior.
Modifying Array Elements
We can modify an existing element in an array by using the assignment operator (=
).
For example, to change the third element in the numbers
array to 10, we would do:
numbers[2] = 10;
Looping Through Arrays
We often use loops to iterate through the elements of an array. For example, we can use a for
loop to print each element in the numbers
array:
for(int i = 0; i < 5; i++) {
cout << numbers[i] << endl;
}
Multidimensional Arrays
C++ also supports multidimensional arrays. The simplest form of a multidimensional array is the two-dimensional array. A 2D array is essentially an array of arrays.
Here's how you can declare a 2D array:
int matrix[3][4];
This declares a 2D array that contains 3 arrays, each with 4 elements.
Arrays are a powerful and versatile data structure in C++. They allow us to store and manipulate large amounts of data efficiently. However, they also come with some limitations, such as a fixed size. In future sections, we will explore more advanced data structures that overcome these limitations.