Thursday, September 20, 2012

program for diagonal elements of a matrix

c program for diagonal elements of a matrix
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20][20],i,j,m,n;
clrscr();
printf("enter the rows and columns of the matrixs\n");
scanf("%d%d",&m,&n);
printf("Enter the first matrics\n");
for(i=0;i<m;i++)
 {
  for(j=0;j<n;j++)
      {
      scanf("%d",&a[i][j]);   //reads the matrics
      }
 }
printf("The diagonal element of the matrics are\n");
for(i=0;i<m;i++)
 {
  for(j=0;j<n;j++)
      {
      if(i==j)
      printf("%d ,",a[i][j]);   //prints the diagonal element of the matrics
      }

 }
 getch();
 }

11 comments:

  1. why here the other diagonal elements not taken (Example for 4x4 matrix---you have taken only a[0][0],a[1][1],a[2][2],a[3][3],a[4][4] are the elements a[0][3],a[1][2],a[2][1],a[3][0] not part of diagonal elements )

    ReplyDelete
  2. In terms of Mathematics, they are not.

    ReplyDelete
  3. Woooow 😉 😃
    Very helpful program
    Thanx a lot 🙏 🙏
    👍 👏 👏

    ReplyDelete
  4. error in the program, as array b and c is unused in the program.

    ReplyDelete
    Replies
    1. Thanks for pointing out the mistake. keeping unused variable is a bad practice but not an error.

      Delete
  5. Row sum and columns sum this only

    ReplyDelete
  6. It's just for 1st diagonal
    Can u complete prog. For 2nd diagonal elements

    ReplyDelete
    Replies
    1. If u want other diagonal value Use
      if((i+j) ==(n-1))

      *remember row and column (m&n) are same in the case of square matrix. So you can take any of the variable from m and n.

      Delete
  7. This comment has been removed by the author.

    ReplyDelete