Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Semrush - keyword research tool

Linux Foundation Training and Certification

Teach Your Child To Read

Disclosure: My content contains affiliate links.

32,307 questions

42,482 answers

573 users

How to find the sum of diagonals of a matrix in Dart

1 Answer

0 votes
import 'dart:io';

int sumDiagonals(List<List<int>>matrix) {
    var rows = matrix.length;
    var cols = matrix[0].length;
    var sumDiagonalLeft = 0;
    var sumDiagonalRigth = 0;
    
    for (var  i = 0; i < rows; i++) {
        sumDiagonalLeft += matrix[i][i];
        sumDiagonalRigth += matrix[i][cols - i - 1];
    }
        
    print("sumDiagonalLeft = " + sumDiagonalLeft.toString());
    print("sumDiagonalRigth = " + sumDiagonalRigth.toString());
        
    return sumDiagonalLeft + sumDiagonalRigth;
}
    
void main() {
    List<List<int>> matrix = [ [1,   2,   3,   4,  0], 
                               [5,   6, 100,   8,  1], 
                               [2, 100,   8, 100,  3], 
                               [1,   7, 100,   9,  6], 
                               [9,  10,  11,  12, 13]];
                               
    // sumDiagonalLeft = (1 + 6 + 8 + 9 + 13) = 37
    // sumDiagonalRigth = (0 + 8 + 8 + 7 + 9) = 32 
  
    // 37 + 32 = 69
    
    stdout.write(sumDiagonals(matrix));
}




/*
run:

sumDiagonalLeft = 37
sumDiagonalRigth = 32
69

*/

 



Learn & Practice Python
with the most comprehensive set of 13 hands-on online Python courses
Start now


answered Jun 19, 2023 by avibootz
...