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 C

1 Answer

0 votes
#include <stdio.h>    

#define COLS 5

int sumDiagonals(int matrix[][COLS], int rows, int cols) {
    int sumDiagonalLeft = 0, sumDiagonalRigth = 0;

    for (int i = 0; i < rows; i++) {
        sumDiagonalLeft += matrix[i][i];
        sumDiagonalRigth += matrix[i][cols - i - 1];
    }

    printf("sumDiagonalLeft = %d\nsumDiagonalRigth = %d\n", sumDiagonalLeft, sumDiagonalRigth);

    return sumDiagonalLeft + sumDiagonalRigth;
}


int main()
{
    int matrix[][COLS] = { { 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

    int rows = sizeof matrix / sizeof matrix[0];
    int cols = sizeof matrix[0] / sizeof(int);

    printf("%d", sumDiagonals(matrix, rows, cols));

    return 0;
}



/*
run:

sumDiagonalLeft = 37
sumDiagonalRigth = 32
69

*/

 



answered Jul 7, 2020 by avibootz
edited Jun 19, 2023 by avibootz

Related questions

2 answers 106 views
2 answers 111 views
2 answers 118 views
1 answer 70 views
1 answer 75 views
1 answer 65 views
1 answer 75 views
...