C++ - Arrays

In C++, an array is a collection of elements of the same data type that are stored in contiguous memory locations. Arrays provide a way to store multiple values of the same type under a single variable name. Here's an explanation of various operations you can perform with arrays:

Access the Elements of an Array:

You can access individual elements of an array using square brackets [] along with the index of the element. The index starts from 0 for the first element and increments by 1 for each subsequent element. Here's an example:

int numbers[] = {1, 2, 3, 4, 5};
int firstNumber = numbers[0];  // Access the first element
int thirdNumber = numbers[2];  // Access the third element

Change an Array Element:

You can modify the value of an array element by assigning a new value using the assignment operator (=). Here's an example:

int numbers[] = {1, 2, 3, 4, 5};
numbers[2] = 10;  // Change the value of the third element to 10

Loop Through an Array:

You can use loops like for or while to iterate over the elements of an array. By using the array's length or size, you can control the number of iterations. Here's an example using a for loop:

int numbers[] = {1, 2, 3, 4, 5};
int length = sizeof(numbers) / sizeof(numbers[0]);
for (int i = 0; i < length; i++) {
    std::cout << numbers[i] << " ";
}

Get the Size of an Array:

To obtain the size of an array, you can divide the total size of the array (in bytes) by the size of a single element (in bytes). Here's an example:

int numbers[] = {1, 2, 3, 4, 5};
int length = sizeof(numbers) / sizeof(numbers[0]);
std::cout << "Size of the array: " << length << std::endl;

Multi-Dimensional Arrays:

C++ supports multi-dimensional arrays, which are arrays of arrays. You can have arrays with two or more dimensions to represent tables, matrices, or other complex data structures.

Access the Elements of a Multi-Dimensional Array:

To access the elements of a multi-dimensional array, you use multiple sets of square brackets, with each bracket representing an index for a specific dimension. Here's an example:

int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
int element = matrix[1][2];  // Access the element at row 1, column 2

Change Elements in a Multi-Dimensional Array:

You can change the value of elements in a multi-dimensional array using the same square bracket notation for assignment. Here's an example:

int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
matrix[0][1] = 10;  // Change the value of the element at row 0, column 1

Loop Through a Multi-Dimensional Array:

To loop through a multi-dimensional array, you can nest loops for each dimension. Here's an example:

int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int row = 0; row < 2; row++) {
    for (int col = 0; col < 3; col++) {
        std::cout << matrix[row][col] << " ";
    }
    std::cout << std::endl;
}