AnkitWebLogic

Find sum of all rows, cols, and diagonals

Q2. WAP to input 3x3 matrix and find sum of all Rows, columns and diagonals. 1

#include<stdio.h>
void main()
{
    int a[3][3], i, j, r1, r2, r3, c1, c2, c3, d1, d2;
	r1=r2=r3=c1=c2=c3=d1=d2=0;
    printf("Enter 3x3 matrix: ");
    for(i=0;i<=2;i++)
    {
        for(j=0;j<=2;j++)
        {
            scanf("%d",&a[i][j]);
        }
    }
    
    printf("\nInput matrix is:\n");
    for(i=0;i<=2;i++)
    {
        for(j=0;j<=2;j++)
        {
            printf("%d  ",a[i][j]);
        }
        printf("\n");
    }
    
    for(i=0;i<=2;i++) //row
    {
        for(j=0;j<=2;j++) //col
        {
            if(i==0)
                r1=r1+a[i][j];
            if(i==1)
                r2=r2+a[i][j];
            if(i==2)
                r3=r3+a[i][j];
            if(j==0)
                c1=c1+a[i][j];
            if(j==1)
                c2=c2+a[i][j];
            if(j==2)
                c3=c3+a[i][j];
            if(i==j)
                d1=d1+a[i][j];
            if(i+j==2)
                d2=d2+a[i][j];
        }
    }
    printf("\nSum of 1st row = %d",r1);
    printf("\nSum of 2nd row = %d",r2);
    printf("\nSum of 3rd row = %d",r3);
    
    printf("\nSum of 1st column = %d",c1);
    printf("\nSum of 2nd column = %d",c2);
    printf("\nSum of 3rd column = %d",c3);
    
    printf("\nSum of 1st diagonal = %d",d1);
    printf("\nSum of 2nd diagonal = %d",d2);
}
Enter 3x3 matrix: 1 2 3 4 5 6 7 8 9
Input matrix is:
1 2 3
4 5 6
7 8 9

Sum of 1st row = 6
Sum of 2nd row = 15
Sum of 3rd row = 24
Sum of 1st column = 12
Sum of 2nd column = 15
Sum of 3rd column = 18
Sum of 1st diagonal = 15
Sum of 2nd diagonal = 15

Advertisement