C++ Multi-Dimensional Arrays
To create a multi-dimensional array in C++, follow these steps:
- Declare the array: Start by declaring the array with the desired number of dimensions and their corresponding sizes. For example, to declare a 2-dimensional array with dimensions 3x4, you would write:
cpp
int array[3][4];
- Initialize the array (optional): If you want to initialize the array with specific values, you can do so using nested braces. Each set of braces represents a dimension of the array. For example, to initialize a 2-dimensional array with the values 1 to 6, you would write:
cpp
int array[2][3] = {{1, 2, 3}, {4, 5, 6}};
Note that if you don't initialize the array, its values will be unpredictable.
- Accessing elements: To access individual elements of a multi-dimensional array, you use the array indices corresponding to each dimension. For example, to access the element at row 1, column 2 of a 2-dimensional array, you would write:
cpp
int value = array[1][2];
Remember that array indices in C++ start from 0, so the first row/column would be accessed using index 0.
- Looping through the array: To iterate over all elements of a multi-dimensional array, you can use nested loops. The outer loop controls the rows, and the inner loop controls the columns. For example, to print all elements of a 2-dimensional array, you would write:
cpp
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << array[i][j] << " ";
}
cout << endl;
}
This will print the array in row-major order.
Remember that in C++, all dimensions of a multi-dimensional array must have a compile-time known size. If you need a dynamically sized multi-dimensional array, you can use pointers and allocate memory using the new
operator.