Print both diagonals of a matrix
C program to read a matrix and print both diagonals.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 10
void main()
{
int mat[MAX][MAX];
int row, col;
int i, j;
printf("Enter the number of rows or columns of the square matrix\t:");
scanf("%d",&row);
col = row;
printf("Enter the elements\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("Element [%d][%d]\t:",i,j);
scanf("%d",&mat[i][j]);
}
}
printf("\n\nMatrix entered is\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d\t",mat[i][j]);
}
printf("\n");
}
printf("\nMain Diagonal element\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
if(i==j)
{
printf("%d\t",mat[i][j]);
}
else
{
printf(" \t");
}
}
printf("\n");
}
printf("\nMinor Diagonal element\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
if(row-i-1==j)
{
printf("%d\t",mat[i][j]);
}
else
{
printf(" \t");
}
}
printf("\n");
}
getch();
}
Output
Enter the number of rows or columns of the square matrix :3
Enter the elements
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
Matrix entered is
1 2 3
4 5 6
7 8 9
Main Diagonal element
1
5
9
Minor Diagonal element
3
5
7