C++ Multidimensional Array
In C++, a multidimensional array is an array of arrays, where each element of the main array holds another array. Multidimensional arrays provide a way to represent tabular or matrix-like structures in which data is organized in rows and columns. Here's how you can work with multidimensional arrays in C++:
Declaration and Initialization:
To declare a multidimensional array, you specify the data type of the elements followed by the array name and the dimensions of the array in square brackets []. The number of square brackets represents the number of dimensions.Accessing Elements:
You can access the elements of a multidimensional array using multiple sets of square brackets, each representing the index in a specific dimension. The indices start from 0 for the first element and go up to size - 1, where size is the size of the corresponding dimension.Nested Loops:
Since a multidimensional array is an array of arrays, you typically use nested loops to iterate over its elements. The outer loop iterates over the rows, and the inner loop iterates over the columns.Jagged Arrays:
C++ also allows the creation of jagged arrays, which are multidimensional arrays with varying sizes in each dimension. Instead of having a regular rectangular shape, jagged arrays have rows of different lengths.Passing Multidimensional Array to Function:
You can pass a multidimensional array to a function by specifying the dimensions in the function parameter. The size of the dimensions except the first must be specified in the function declaration to ensure proper array traversal.
int matrix[3][3]; // Declaration of a 3x3 integer matrix
float table[4][5] = {{1.0, 2.0}, {3.0, 4.0, 5.0}}; // Declaration and initialization of a 4x5 float table
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int element = matrix[1][2]; // Access the element at row 1, column 2
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
int jaggedArray[3][];
jaggedArray[0] = new int[2];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[3];
void printMatrix(int arr[][3], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
int main() {
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
printMatrix(matrix, 2);
return 0;
}
Multidimensional arrays are useful for representing structured data, such as grids, tables, matrices, or any other data organized in multiple dimensions. They provide a flexible way to store and access data in a tabular format, enabling you to perform operations on rows, columns, or individual elements as needed.