Menu BAR

FEEL FREE TO ASK ANY PROGRAM and please mention any error if you find it

22 Feb 2013

Sum of diagonal elements in Matrix

Q)Write a C program to find the sum of diagonal elements in  matrix.
Hint: 
        1    2    3
        4    5    6
        7    8    9
First diagonal elements are 1,5,9
Second diagonal elements are 3,5,7.

Sol)
 

#include<stdio.h>
#include<conio.h>
#define MAX 5

int main()
{
    int mat[MAX][MAX],row,col ;
    int i,j,d1=0,d2=0 ;

    printf("Enter no. of rows and columns : ") ;
    scanf("%d%d",&row,&col) ;

    printf("Enter the elements of matrix: \n") ;
    if(row==col)
       {
             for(i=0; i<row; i++)
                   {
                         for(j=0; j<col; j++)
                                 scanf("%d",&mat[i][j]) ;
                     }
              for(i=0, j=col-1; i<row || j>=0; i++,j--)
                     {
                             d1=d1+mat[i][i] ;
                             d2=d2+mat[i][j] ;
                      }
            
               printf("\nThe sum of first diagonal elements : %d", d1) ;
               printf("\n The sum of second diagonal elements : %d", d2) ;
         }
     else
          {
                printf("Rows and Columns are not equal !!") ;
                printf("\n Try again !!") ;
           }

      getch();
      return 0;
}

                                    :::::OUTPUT::::

Enter no. of rows and columns : 3  2
Enter the elements of matrix:
Rows and Columns are not equal !!
Try again !!
  
Enter no of rows and columns : 3  3
Enter the elements of matrix:
1   2   3
4   5   6
7   8   9
The sum of first diagonal elements : 15
The sum of second diagonal elements : 15

2 comments:

  1. 1 2 3
    4 5 6
    7 8 9

    In above 3X3 matrix there are two types diagonal element as:
    first diagonal elements are 1, 5, 9 and
    second diagonal elements are 3, 5,7

    please find attached the program to find the sum of diagonals of a matrix.

    for an indepth understanding please visit the following link:
    http://www.fixoncloud.com/Home/LoginValidate/OneProblemComplete_Detailed.php?problemid=327

    ReplyDelete
  2. can you write this program in c++

    ReplyDelete