Print numbers in matrix diagonal pattern in C Program.

The task is to print the matrix of n x n of the diagonal pattern.

If n is 3 then to print a matrix in Diagonal pattern is −

So the output will be like −

Example

Input: 3
Output:
   1 2 4
   3 5 7
   6 8 9
Input: 4
Output:
   1 2 4  7
   3 5 8 11
   6 9 12 14
   10 13 15 16

The problem suggests we have to give a number n and generate a matrix of n x n and then we have to traverse the matrix in a diagonal pattern and store the values in a separate matrix.

But this will increase the complexity of our code, so we will −

  • Create a matrix of size N X N which will store the pattern before printing.

  • Store the elements in the upper triangle of the pattern. As observed the row index increases by 1 and the column index decreases by 1 as you move down the diagonal.

  • Once the upper triangle is completed then store the elements of the lower triangle in a similar way as the upper triangle i.e. row index increases by 1 and column index decreases by 1 as you move down the diagonal.

Algorithm

int printdiagonal(int n)
START
STEP 1: DECLARE int mat[n][n], i, j, k, d=1, m
STEP 2: LOOP FOR i = 0 AND i = 0 AND j--
      ASSIGN mat[k][j] AS d
      INCREMENT d AND k BY 1
   END LOOP
END LOOP
STEP 3: LOOP FOR k = 1 AND k = m AND j--
      ASSIGN mat[i][j] AS d;
      INCREMENT d AND i WITH 1
   END FOR
END FOR
STEP 4: LOOP FOR i = 0 AND i 

Example

#include 
int printdiagonal(int n){
   int mat[n][n], i, j, k, d=1, m;
   for ( i = 0; i = 0; j--){
         mat[k][j] = d;
         d++;
         k++;
      }
   }
   for ( k = 1; k = m; j--){
         mat[i][j] = d;
         d++;
         i++;
      }
   }
   for ( i = 0; i ");
   }
}
int main(int argc, char const *argv[]){
   int n = 3;
   printdiagonal(n);
   return 0;
}

Output

If we run the above program then it will generate the following output −

1 2 4
3 5 7
6 8 9
Updated on: 2019-08-22T08:54:13+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements