Easy Tutorial
❮ C Function Vfprintf C Exercise Example73 ❯

C Exercise Example 38

C Language Classic 100 Examples

Title: Calculate the sum of diagonal elements of a 3*3 matrix.

Program Analysis: Use a double for loop to control the input of a two-dimensional array, then accumulate and output the sum of a[i][i].

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015 tutorialpro.org. All rights reserved.
//

#include<stdio.h>
#define N 3
int main()
{
    int i,j,a[N][N],sum=0;
    printf("Please enter the matrix (3*3):\n");
    for(i=0;i&lt;N;i++)
        for(j=0;j&lt;N;j++)
            scanf("%d",&a[i][j]);
    for(i=0;i&lt;N;i++)
        sum+=a[i][i];
    printf("The sum of the diagonals is: %d\n",sum);
    return 0;
}

The output of the above example is:

Please enter the matrix (3*3):
1 2 3
4 5 6
7 8 9
The sum of the diagonals is: 15

C Language Classic 100 Examples

❮ C Function Vfprintf C Exercise Example73 ❯