C program to find sum of diagonal elements of a matrix

C program to find sum of diagonal elements of a matrix

  1. #include<stdio.h>
  2. int main()
  3. {
  4.  int a[3][3], i, j, total=0;
  5. //Loops for Reading the matrix
  6.  for ( i = 0; i < 3; i++ ) //related to row
  7.  { 
  8.    for ( j = 0; j < 3; j++ ) //related to column
  9.    { 
  10.     printf("Element[%d][%d]:",i,j);
  11.      scanf("%d", &a[i][j]) ;
  12.    }   
  13.  } 
  14. //Loops to find total
  15.  for ( i = 0; i < 3; i++ ) //related to row
  16.  { 
  17.    for ( j = 0; j < 3; j++ ) //related to column
  18.    { 
  19.     if(i==j)
  20.       total = total + a[i][j];
  21.    }   
  22.  } 
  23.  printf("Sum of Diagonal elements of Matrix A: %d", total);
  24.  return 0;
  25.  

Output


Element[0][0]:2
Element[0][1]:3
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: 17

Choose next program from this list

Comments