Print elements of a matrix in diagonal order

Given a square matrix of order N*N, write code to print all the elements in the order of their diagonal.

For example, in the below matrix, the elements should be printed in the marked (in red) order, and the final output should be as shown below:


Solution:

We did a similar question yesterday, that was to print two diagonals of the matrix. The code to print all the elements will be similar. Basically we will be printing one small diagonal at a time. There will be total 2*n-1 such diagonals (each arrow represents one diagonal in the above diagram).

Code:

#define N 4
void printAllDgl(int a[N][N])
 {
    int i=0, j=0;
   // Loop to print each diagonal
    for(int cnt=0; cnt<2*N-1; cnt++)
    {
       cout<<std::endl;
       if(cnt<N) {
          i = cnt;
         j = 0;
       }
       else {
          i = N-1;
         j = (cnt+1)%N;
       }
       while(i>=0 && j<N)
       {
          cout << " " << a[i][j];
          i--;
         j++;
       }
   }
}
Feel free to give your feedback and comments. 

0 Comments

Leave a comment