Nested loops solve many real-world problems involving multi-dimensional data.
Finding Maximum in 2D Array
function findMaxInMatrix(matrix) {
let max = matrix[0][0];
for (let row of matrix) {
for (let value of row) {
if (value > max) {
max = value;
}
}
}
return max;
}
const scores = [
[85, 92, 78, 90],
[88, 95, 82, 87],
[90, 88, 93, 85]
];
console.log("Highest score:", findMaxInMatrix(scores)); // 95
Search through all elements in a 2D array to find the maximum value.
Matrix Transposition
function transposeMatrix(matrix) {
const rows = matrix.length;
const cols = matrix[0].length;
const transposed = [];
for (let j = 0; j < cols; j++) {
transposed[j] = [];
for (let i = 0; i < rows; i++) {
transposed[j][i] = matrix[i][j];
}
}
return transposed;
}
const original = [
[1, 2, 3],
[4, 5, 6]
];
const transposed = transposeMatrix(original);
console.log("Original:", original);
console.log("Transposed:", transposed);
// Output:
// Original: [[1, 2, 3], [4, 5, 6]]
// Transposed: [[1, 4], [2, 5], [3, 6]]
Swap rows and columns using nested loops.
Pattern Generation
function printPattern(size) {
for (let i = 1; i <= size; i++) {
let row = '';
for (let j = 1; j <= i; j++) {
row += '* ';
}
console.log(row.trim());
}
}
printPattern(5);
// Output:
// *
// * *
// * * *
// * * * *
// * * * * *
Generate patterns using nested loops with different iteration ranges.
Multiplication Table
function printMultiplicationTable(size) {
for (let i = 1; i <= size; i++) {
let row = '';
for (let j = 1; j <= size; j++) {
row += (i * j) + ' ';
}
console.log(row);
}
}
printMultiplicationTable(5);
// Output:
// 1 2 3 4 5
// 2 4 6 8 10
// 3 6 9 12 15
// 4 8 12 16 20
// 5 10 15 20 25
Generate multiplication tables using nested loops.