Write a calculation and output the sum of the diagonal elements of a matrix of order 33.

Hits: 0

Write a calculation and output the sum of the diagonal elements of a matrix of order 3*3.

Example of program running result:
Please input [array] elements: (3*3)↙
1 2 3 4 5 6 7 8 9↙
↙ The
array is: ↙
1 2 3 ↙
4 5 6↙
7 8 9 ↙

The sum of the diagonals: ↙
25↙

Input prompt: “Please input array element: (3*3)\n”
Input format: “%d”
Output prompt: “\nArray is:\n”
Output format: “%4d”
Output prompt: “\nYes Sum of angle lines:\n”
Output format:”%d\n”

# include <stdio.h> 
int  main ()
 {
     int a[ 3 ][ 3 ],i,j,sum= 0 ;
     printf ( "Please enter array elements: (3*3)\n" );
     for (i = 0 ; i< 3 ; i++)
    {
        for(j=0;j<3;j++)
        {
            scanf("%d",&a[i][j]);
            if(i==j||(i==2&&j==0)||(i==0&&j==2))
            {
                sum+=a[i][j];
            }
        }
    }
    printf ( "\nArray is:\n" );
     for (i= 0 ;i< 3 ;i++)
    {
        for(j=0;j<3;j++)
        {
            printf("%4d",a[i][j]);
        }
        printf("\n");
    }
    printf ( "\nSum of diagonals:\n" );
     printf ( "%d\n" ,sum);
}

Leave a Reply

Your email address will not be published.