A multidimensional array in C++ is an array that has more than one dimension. The most common form of multidimensional arrays are two-dimensional arrays, but you can have arrays with more dimensions (3D, 4D, etc.).
Two-Dimensional Array (2D Array)
A two-dimensional array can be thought of as an array of arrays. It’s often used to represent tables, grids, or matrices.
Syntax:
type arrayName[rowSize][columnSize];
Explanation:
- rowSize represents the number of rows
- columnSize represents the number of columns.
Example:
#include <iostream>
using namespace std;
int main() {
// Declare a 2D array with 2 rows and 3 columns
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
// Accessing and printing elements of the 2D array
for (int i = 0; i < 2; i++) { // Loop through rows
for (int j = 0; j < 3; j++) { // Loop through columns
cout << arr[i][j] << " ";
}
cout << endl; // New line after each row
}
return 0;
}
Explanation:
- int arr[2][3]: This declares a 2D array with 2 rows and 3 columns.
- arr[i][j]: This accesses the element at the i-th row and j-th column.
Output:
1 2 3
4 5 6
4 5 6