Home Tutorial C Sum of diagonal of Matrix in C

 
 

Sum of diagonal of Matrix in C
Posted on: December 26, 2009 at 12:00 AM
In this section, you will learn how to find the sum of diagonals of a matrix in C Program.

C Sum of diagonal of Matrix

In this section, you will learn how to determine the sum of both the diagonal of 3X3 matrix. For this, we have declared an array of integers and using the for loops, we have determined the sum of both the diagonals.

Here is the code:

#include <stdio.h>
#include
<conio.h>

void main() {
        int d[3][3] = { 1, 2, 6, 3, 8, 5, 5, 6, 7 };
        int k = 0, j = 0;
        int sum1 = 0, sum2 = 0;
        for (j = 0; j < 3; j++) {
                 for (k = 0; k < 3; k++)
             printf(" %3d", d[j][k]);
             printf("\n");
        }
        for (j = 0; j < 3; j++) {
             sum1 = sum1 + d[j][j];
        }
        k = 3 - 1;
        for (j = 0; j < 3; j++) {
             if (k >= 0) {
             sum2 = sum2 + d[j][k];
             k--;
             }
           }
        printf("Sum of First diagonal= %d\n", sum1);
        printf("Sum of Second diagonal= %d", sum2);
        getch();
}

Output:

1    2     6
3    8     5
5    6     7
Sum of First diagonal=16
Sum of Second diagonal=19

Related Tags for Sum of diagonal of Matrix in C :


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.