Saturday, February 6, 2016

C program to find sum of diagonal elements of a matrix.

#include<stdio.h>
int main()
{
int a[3][3], i, j, total=0;
//Loops for Reading the matrix
for ( i = 0; i < 3; i++ ) //related to row

  for ( j = 0; j < 3; j++ ) //related to column
  { 
  printf("Element[%d][%d]:",i,j);
    scanf("%d", &a[i][j]) ;
  }

//Loops to find total
for ( i = 0; i < 3; i++ ) //related to row

  for ( j = 0; j < 3; j++ ) //related to column
  { 
  if(i==j)
    total = total + a[i][j];
  }

printf("Sum of Diagonal elements of Matrix A: %d", total);
 return 0;


Output of program

Element[0][0]:1
Element[0][1]:2
Element[0][2]:3
Element[1][0]:4
Element[1][1]:5
Element[1][2]:6
Element[2][0]:7
Element[2][1]:8
Element[2][2]:9
Sum of Diagonal elements of Matrix A: 15


No comments:

Post a Comment