Share on Google+Share on Google+

Sum of diagonal of Matrix in C

Advertisement
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

Advertisements

Posted on: December 26, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.