Shyam Shingadiya Shyam Shingadiya -4 years ago 141
PHP Question

Calculate sum of Primary and Secondary Diagonal in square matrix

I am currently calculating diagonal for

n x n
square matrix. I can able to calculate Primary diagonal with below code.

function calculateDiagonal($array) {
$length = count($array);
$primary = 0;
$secondary = 0;
for ($i = 0; $i < $length; $i++):
for ($j = 0; $j < $length; $j++):
if ($i == $j):
$primary += $array[$i][$j];
endif;
endfor;
endfor;
$totalSum = $primary + $secondary;
return $totalSum;
}


Can anyone help me to calculate sum of secondary diagonal.

check this as a reference.
enter image description here

Answer Source

Please try with this. You can do sum of diagonal with minimum iteration.

    $a = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]];
    $n = 4;//nxn matrix
    $d = $s = 0; //initialize both diagonal sum to 0
    for ($i = 0; $i < $n; $i++) {
        $d += $a[$i][$i];
        $s += $a[$i][$n - $i - 1]; 
    }
    var_dump($d);//primary diagonal total
    var_dump($s);//secondary diagonal total
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download