Print a matrix diagonally upward
C program to print a matrix diagonally upward.
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_up(int mat[MAX][MAX], int row, int col)
{
int i;
int cur_row, cur_col;
for(i=0;i<row;i++)
{
cur_row = i;
cur_col = 0;
while(cur_row >= 0 && cur_col < col)
{
printf("%d ",mat[cur_row][cur_col]);
cur_row--;
cur_col++;
}
}
for(i=0;i<col-1;i++)
{
cur_row = row-1;
cur_col = i+1;
while(cur_col < col && cur_row >= 0)
{
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_up(mat, row, col);
getch();
}
Output
Enter the number of rows :3
Enter the number of columns :8
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 [0][6] :7
Element [0][7] :8
Element [1][0] :9
Element [1][1] :10
Element [1][2] :11
Element [1][3] :12
Element [1][4] :13
Element [1][5] :14
Element [1][6] :15
Element [1][7] :16
Element [2][0] :17
Element [2][1] :18
Element [2][2] :19
Element [2][3] :20
Element [2][4] :21
Element [2][5] :22
Element [2][6] :23
Element [2][7] :24
Matrix entered is
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
Matrix in snake from last column form is
1 9 2 17 10 3 18 11 4 19 12 5 20 13 6 21 14 7 22 15 8 23 16 24