Sum of the diagonals of a matrice

Klecianny Melo - Feb 1 - - Dev Community

Prepare your favorite cup of coffee because we are about to enter the fantastic world of Matrices.

What is a matrice?

A matrice is a data structure that has rows and columns. Each element will have its location made up of two numbers, the first referring to the row and the second referring to the column.

Let's learn how to calculate the sum of the diagonals of a matrice using JavaScript.

const matrice = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
Enter fullscreen mode Exit fullscreen mode

The main diagonal of the matrice is made up of the elements that are in the same row and column, those where row = column

console.log(matrice[0][0]); // 1 (first row, first column)
console.log(matrice[1][1]); // 5 (second row, second column)
console.log(matrice[2][2]); // 9 (third row, third column)
Enter fullscreen mode Exit fullscreen mode

To calculate the main diagonal, we will iterate over the elements of the matrice and add those that are in the same row and column.

// Function to calculate the main diagonal
const mainDiagonalSum = (matrice) => {
    // Variable that will store the sum
    var sum = 0;

    // Iterating over all elements of the matrice
    for (var i = 0; i < matrice.length; i++) {
        // Sum of diagonal elements
        sum += matrice[i][i];
    }

    // Returns the final sum
    return sum;
}

console.log(mainDiagonalSum(matrice)); // 15 (1 + 5 + 9)
Enter fullscreen mode Exit fullscreen mode

The secondary diagonal of the matrice is formed by the elements where column = matrice size - 1 - row

console.log(matrice.length); // 3

console.log(matrice[0][3 - 1 - 0]); // 3 (first row, third column)
console.log(matrice[1][3 - 1 - 1]); // 5 (second row, second column)
console.log(matrice[2][3 - 1 - 2]); // 7 (third row, first column)

// Function to calculate the secondary diagonal
const secondaryDiagonalSum = (matrice) => {
    // Variable that will store the sum
    var sum = 0;

    // Iterating over all elements of the matrice
    for (var i = 0; i < matrice.length; i++) {
        // Sum of the elements of the secondary diagonal
        sum += matrice[i][matrice.length - 1 - i];
    }

    // Returns the final sum
    return sum;
}

console.log(secondaryDiagonalSum(matrice)); // 15 (3 + 5 + 7)
Enter fullscreen mode Exit fullscreen mode

Share the code, spread knowledge and build the future! 😉

. . . . . . . . . . . . . . . . . . . . . . . .