Multidimensional Arrays

2D and 3D arrays

Interview Relevant: Matrix problems

Multidimensional Arrays

Arrays of arrays for representing matrices and grids.

Code Examples

2D arrays for matrix operations.

cpp
1// 2D array declaration
2int matrix[3][4];  // 3 rows, 4 columns
3
4// Initialize 2D array
5int grid[2][3] = {
6    {1, 2, 3},
7    {4, 5, 6}
8};
9
10// Access elements
11grid[0][0] = 10;  // First element
12grid[1][2] = 60;  // Last element
13
14// Iterate 2D array
15for (int i = 0; i < 2; i++) {
16    for (int j = 0; j < 3; j++) {
17        cout << grid[i][j] << " ";
18    }
19    cout << endl;
20}
21
22// Using vector for dynamic 2D array
23vector<vector<int>> dynamic2D(3, vector<int>(4, 0));
24dynamic2D[1][2] = 5;

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In