C++ Multi-Dimensional Arrays
In C++, a multi-dimensional array is an array of arrays. It allows you to store and manipulate collections of data in a structured manner, where each element can be accessed by specifying multiple indices.
There are two ways to declare a multi-dimensional array in C++: using a single set of square brackets or using multiple sets of square brackets. The first approach is called a row-major order, and the second approach is called a column-major order.
Example: Row-Major Order
1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 int matrix[2][3]; 7 8 cout << "Enter 6 elements:" << endl; 9 for (int i = 0; i < 2; i++) 10 { 11 for (int j = 0; j < 3; j++) 12 { 13 cin >> matrix[i][j]; 14 } 15 } 16 17 cout << "The elements of the matrix are:" << endl; 18 for (int i = 0; i < 2; i++) 19 { 20 for (int j = 0; j < 3; j++) 21 { 22 cout << matrix[i][j] << " "; 23 } 24 cout << endl; 25 } 26 27 return 0; 28}
Output:
1Enter 6 elements: 21 32 43 54 65 76 8The elements of the matrix are: 91 2 3 104 5 6
In the above example, matrix[2][3]
declares a 2x3 matrix, where matrix[i][j]
accesses the element located at the i
th row and the j
th column of the matrix.
Example: Column-Major Order
1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 int matrix[3][2]; 7 8 cout << "Enter 6 elements:" << endl; 9 for (int j = 0; j < 2; j++) 10 { 11 for (int i = 0; i < 3; i++) 12 { 13 cin >> matrix[i][j]; 14 } 15 } 16 17 cout << "The elements of the matrix are:" << endl; 18 for (int i = 0; i < 3; i++) 19 { 20 for (int j = 0; j < 2; j++) 21 { 22 cout << matrix[i][j] << " "; 23 } 24 cout << endl; 25 } 26 27 return 0; 28}
Output:
1Enter 6 elements: 21 32 43 54 65 76 8The elements of the matrix are: 91 4 102 5 113 6
In the above example, matrix[3][2]
declares a 3x2 matrix, where matrix[i][j]
accesses the element located at the i
th column and the j
th row of the matrix.