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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

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

1 Answer

0 votes
fun sumDiagonals(matrix: Array<IntArray>, rows: Int, cols: Int): Int {
    var sumDiagonalLeft = 0
    var sumDiagonalRight = 0

    for (i in 0 until rows) {
        for (j in 0 until cols) {
            if (i == j) {
                sumDiagonalLeft += matrix[i][j]
            }
            if (i + j == rows - 1) {
                sumDiagonalRight += matrix[i][j]
            }
        }
    }

    println("sumDiagonalLeft = $sumDiagonalLeft \nsumDiagonalRigth = $sumDiagonalRight")

    return sumDiagonalLeft + sumDiagonalRight
}

fun main() {
    val matrix = arrayOf(
        intArrayOf(1,   2,   3,   4,  0),
        intArrayOf(5,   6, 100,   8,  1),
        intArrayOf(2, 100,   8, 100,  3),
        intArrayOf(1,   7, 100,   9,  6),
        intArrayOf(9,  10,  11,  12, 13)
    )
    
    // sumDiagonalLeft = (1 + 6 + 8 + 9 + 13) = 37
    // sumDiagonalRigth = (0 + 8 + 8 + 7 + 9) = 32 
   
    // 37 + 32 = 69

    val rows = matrix.size
    val cols = matrix[0].size

    println(sumDiagonals(matrix, rows, cols))
}

 
 
 
/*
run:

sumDiagonalLeft = 37 
sumDiagonalRigth = 32
69
 
*/

 



answered Dec 19, 2024 by avibootz
...