Theory
A two-dimensional array is an array containing other arrays. It is commonly used to represent matrices, tables and grids. We generally use nested loops to access all elements.
Example
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
for (const row of matrix) {
for (const value of row) {
console.log(value);
}
}
Expected Output
The values from 1 to 9 are printed row by row.
Practice
Create a 3×3 matrix and calculate the sum of all its elements.
Interview Questions
- What is a two-dimensional array?
- Where are matrices used?
- Why are nested loops commonly used with 2D arrays?
- What is a matrix?