PRINT MATRIX DIAGONALLY
Given a 2D array, write a program to print all elements of the given matrix in diagonal order. 

For example, consider the following 5 X 4 input matrix. 
    1     2     3     4 
    5     6     7     8 
    9    10    11    12 
   13    14    15    16 
   17    18    19    20 
Diagonal printing of the above matrix is 
    1 
    5     2 
    9     6     3 
   13    10     7     4 
   17    14    11     8 
   18    15    12 
   19    16 
   20 
  
Input and Output Format: 
The first line of the input consists of an integer, r that corresponds to the number of rows in the matrix. 
The next line of the input consists of an integer, c that corresponds to the number of columns in the matrix. 
The next 'm*n' lines in the input corresponds to the elements in the matrix. 
Output is a matrix. 
  
Sample Input: 
1 2 3 4 
5 6 7 8 
9 10 11 12 
13 14 15 16 
17 18 19 20 

Sample Output: 
5  2 
9  6  3 
13  10  7  4 
17  14  11  8 
18  15  12 
19  16 
20 


Program Code:
#include <stdio.h>
int main()
{
int rows, cols, rowCounter, colCounter;
int inputMatrix[50][50];
scanf("%d %d", &rows, &cols);
for(rowCounter = 0; rowCounter < rows; rowCounter++)
{
for(colCounter = 0; colCounter < cols; colCounter++)
{
scanf("%d", &inputMatrix[rowCounter][colCounter]);
}
}
int row, col,k;
for (k = 0; k < rows; k++) 
{
for (row = k, col = 0; row >= 0 && col < cols; row--, col++) 
{
printf("%d  ",inputMatrix[row][col]);
}
printf("\n");
}
 for (k = 1; k < cols; k++) 
{
for (row = rows - 1, col = k; row >= 0 && col < cols; row--, col++) 
{
printf("%d  ",inputMatrix[row][col]);
}
printf("\n");
}
printf("\n");
}
return 0;
}
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: