C program to find sum of all diagonal elements of a matrix | My CS Tutorial - My CS Tutorial

Breaking

Programming languages full tutorial and programs, exam papers, visual basic( Vb.net ), information of new technologies and more....

Thursday, February 20, 2020

C program to find sum of all diagonal elements of a matrix | My CS Tutorial


C program to find sum of diagonal of matrix. C program to find sum of right diagonal of a matrix. C program to find sum of left diagonal of matrix.

C program to find sum of all diagonal elements of a matrix | My CS Tutorial


In this tutorial we will learn  or discuss that how to write a c program code to find sum of diagonal elements of a matrix. In this program we will use arrays.

This c program code will find the sum of both left and right diagonal elements of a matrix.

In the first user will enter range of rows and columns of matrix. After it user enter the elements of first matrix.

After it compiler check and exicute the condition and logics and print given matrix and print the given matrix and print the sum of both or all diagonal elements of a matrix.


C PROGRAM CODE



#include<stdio.h>
#include<conio.h>
void main()
{
 int i,j,rows,col,diagonal_1=0,diagonal_2=0,m,n;
 int a[100][100];
 clrscr();
 printf("\n ENTER NUMBER OF ROWS:\n ");
 scanf("%d %d",&rows,&col);

 if(col==rows)
 {
  m=0;
  n=rows-1;
   //Taking input for matrix
 printf("\n ENTER ELEMENTS OF MATRIX:\n ");
  for(i=0;i<rows;i++)
  {
  for(j=0;j<col;j++)
  {
   scanf("%d",&a[i][j]);
  }
  }
  printf("\n THE GIVEN MATRIX IS:\n ");
  
  for(i=0;i<rows;i++)
  {
  for(j=0;j<col;j++)
  {
   printf("%d\t",a[i][j]);
  }
  printf("\n ");
  }

  for(i=0;i<rows;i++)
  {
   diagonal_1+=a[i][i];
   diagonal_2+=a[m][n];
   m++;
   n--;
  }
  
  printf("\n SUM OF FIRST DIAGONAL IS:\n %d",diagonal_1);
  printf("\n SUM OF ANOTHER DIAGONAL IS:\n %d",diagonal_2);
}
 else
 {
  printf("\n NOT POSSIBLE.......\n ");
 }

getch();
}


OUTPUT:





Please share this post and blog link with your friends.For more programs use this blog.
If you have any problem, please comment in comment box, subscribe this blog for notifications of new post on your email and follow this blog.If you have any method of this program or want to give any suggestion send email on hc78326@gmail.com

Created by-- HARSH CHAUHAN


No comments:

Post a Comment