multi dimensional arrays in cpp
multi dimensional arrays in cpp
Multi-dimensional arrays in C++ are arrays that contain more than one dimension. They are useful for storing tabular or grid-like data, such as matrices, tables, or game boards.
The most commonly used multi-dimensional array is the two-dimensional array.
A multi-dimensional array is an array of arrays. Each element is accessed using multiple indices.
General Syntax:
dataType arrayName[size1][size2]...[sizeN];
size1
– Number of rows
size2
– Number of columns (for 2D)
sizeN
– Additional dimensions if needed
#include <iostream>
using namespace std;
int main() {
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output:
1 2 3
4 5 6
#include <iostream>
using namespace std;
int main() {
int cube[2][2][2] = {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
cout << cube[i][j][k] << " ";
}
cout << endl;
}
cout << "---" << endl;
}
return 0;
}
Output:
1 2
3 4
---
5 6
7 8
---
Multi-dimensional arrays are stored in row-major order in memory.
The elements are stored contiguously.
For example, matrix[2][3]
stores elements in the order:matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], matrix[1][1], matrix[1][2]
Organize data in tabular or grid form
Easy to represent mathematical matrices
Useful in game boards, graphs, and scientific computations
Fixed size at compile time
Consumes more memory for large dimensions
Complex indexing for higher dimensions
Multi-dimensional arrays in C++ are essential for storing and processing data in table-like structures. Two-dimensional arrays are the most common, but you can extend to three or more dimensions when needed.