How to find the sum of each row and each column of a matrix (2D array) in TypeScript

1 Answer

0 votes
const arr : number[][] = [
    [1, 2, 3, 5],
    [4, 5, 6, 5],
    [7, 8, 9, 5]
];
  
const rows : number = arr.length;
const cols : number = arr[0].length;
  
for (let i : number = 0; i < rows; i++) {
    let sumRow = 0
    for (let j : number = 0; j < cols; j++) {
        sumRow = sumRow + arr[i][j];  
    }
    console.log("Sum of row:" + i + " = " + sumRow); 
}
 
for (let i : number = 0; i < cols; i++) {
    let sumCol = 0
    for (let j : number = 0; j < rows; j++) {
        sumCol = sumCol + arr[j][i];  
    }
    console.log("Sum of col:" + i + " = " + sumCol); 
}
 
 
 
               
      
/*
run:

/*
run:
      
"Sum of row:0 = 11"
"Sum of row:1 = 20"
"Sum of row:2 = 29"
"Sum of col:0 = 12"
"Sum of col:1 = 15"
"Sum of col:2 = 18"
"Sum of col:3 = 15"
     
*/
     

 



answered Nov 20, 2022 by avibootz
...