Example:
If the array elements are:
1 2 3
4 5 6
7 8 9
Output: Sum of main diagonal elements = 15
Required knowledge:
Basic C programming, For loop, Array, MatrixMain diagonal of matrix
Main diagonal of a matrix A is a collection of elements Aij Such that i = j.Program:
/**
* C program to find sum of main diagonal elements of a matrix
*/
#include <stdio.h>
int main()
{
int A[3][3];
int row, col, sum = 0;
/*
* Reads elements in matrix from user
*/
printf("Enter elements in matrix of size 3x3: \n");
for(row=0; row<3; row++)
{
for(col=0; col<3; col++)
{
scanf("%d", &A[row][col]);
}
}
/*
* Finds the sum of main diagonal elements
*/
for(row=0; row<3; row++)
{
sum = sum + A[row][row];
}
printf("\nSum of main diagonal elements = %d", sum);
return 0;
}
Output
Enter elements in matrix of size 3x3:
1 2 3
4 5 6
7 8 9
Sum of main diagonal elements = 15
1 2 3
4 5 6
7 8 9
Sum of main diagonal elements = 15
Happy coding ;)
You may also like
- Array and Matrix programming exercises index.
- C program to add two matrices.
- C program to find sum of opposite diagonal elements of a matrix.
- C program to find sum of elements of each row and columns of a matrix.
- C program to find lower triangular matrix.
- C program to find upper triangular matrix.
- C program to interchange diagonals of a matrix.
- C program to find sum of elements of an array.
- C program to find maximum and minimum elements in an array.
- C program to find reverse of an array.
- C program to sort elements of an array in ascending order.
- C program to print Fibonacci series up to n terms.
- C program to print Pascal triangle.
- C program to create a Simple Calculator using switch case.