Dremendo Tag Line

Input numbers in 2d array and find the sum of each row, column, right and left diagonal in C

Two Dimensional Array - Question 7

In this question, we will see how to input numbers in a 3X3 integer matrix (2d array) and find the sum of each row, each column, right diagonal and left diagonal separately in C programming. To know more about two dimensional array click on the two dimensional array lesson.

Q7) Write a program in C to input numbers in a 3X3 integer matrix (2d array) and find the sum of each row, each column, right diagonal and left diagonal separately. Right Diagonal = / and Left Diagonal = \.

Program

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

int main()
{
    int a[3][3], r,c,rs,cs,rd=0,ld=0;

    printf("Enter 9 numbers\n");
    for(r=0; r<3; r++)
    {
        for(c=0; c<3; c++)
        {
            scanf("%d",&a[r][c]);
        }
    }

    for(r=0; r<3; r++)
    {
        rs=0;
        cs=0;
        ld=ld+a[r][r];
        rd=rd+a[r][2-r];
        for(c=0; c<3; c++)
        {
            printf("%d ",a[r][c]);
            rs=rs+a[r][c];		// row sum
            cs=cs+a[c][r];		// column sum
        }
        printf("  Row Sum = %d  Column Sum = %d\n",rs,cs);
    }
    printf("Left Diagonal Sum = %d\n",ld);
    printf("Right Diagonal Sum = %d",rd);
    return 0;
}

Output

Enter 9 numbers
18
12
72
10
15
45
38
5
64
18 12 72   Row Sum = 102  Column Sum = 66
10 15 45   Row Sum = 70  Column Sum = 32
38 5 64   Row Sum = 107  Column Sum = 181
Left Diagonal Sum = 97
Right Diagonal Sum = 125
video-poster