Print a matrix diagonally downward
C program to print a matrix diagonally downward.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 10
void read_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("Element [%d][%d]\t:",i,j);
scanf("%d",&mat[i][j]);
}
}
}
void print_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d\t",mat[i][j]);
}
printf("\n");
}
}
void print_diag_down(int mat[MAX][MAX], int row, int col)
{
int i;
int cur_row, cur_col;
for(i=0;i<col;i++)
{
cur_row = 0;
cur_col = i;
while(cur_row < row && cur_col >=0)
{
printf("%d ",mat[cur_row][cur_col]);
cur_row++;
cur_col--;
}
}
for(i=0;i<row-1;i++)
{
cur_row = i+1;
cur_col = col-1;
while(cur_col >= 0 && cur_row < row)
{
printf("%d ",mat[cur_row][cur_col]);
cur_row++;
cur_col--;
}
}
}
void main()
{
int mat[MAX][MAX];
int row, col;
printf("Enter the number of rows\t:");
scanf("%d",&row);
printf("Enter the number of columns\t:");
scanf("%d",&col);
printf("Enter the elements of the matrix\n");
read_matrix(mat, row, col);
printf("\nMatrix entered is\n");
print_matrix(mat, row, col);
printf("\nMatrix in snake from last column form is \n");
print_diag_down(mat, row, col);
getch();
}
Output
Enter the number of rows :3
Enter the number of columns :6
Enter the elements of the matrix
Element [0][0] :1
Element [0][1] :2
Element [0][2] :3
Element [0][3] :4
Element [0][4] :5
Element [0][5] :6
Element [1][0] :7
Element [1][1] :8
Element [1][2] :9
Element [1][3] :10
Element [1][4] :11
Element [1][5] :12
Element [2][0] :13
Element [2][1] :14
Element [2][2] :15
Element [2][3] :16
Element [2][4] :17
Element [2][5] :18
Matrix entered is
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
Matrix in snake from last column form is
1 2 7 3 8 13 4 9 14 5 10 15 6 11 16 12 17 18