Skip to main content

Print Diagonally

Task: Given a N*N matrix, print the values of matrix in anti diagonal way.

Example:
Input:
1
1 2 3
4 5 6 
7 8 9
Output:
1 2 4 5 6 7 6 8 9 // 1-2,4-3,5,7-6,8-9.

Here is the Code:
Program in C++:

  1. #include<iostream>
  2. using namespace std;
  3. int main()
  4.  {
  5. int t;
  6. cin>>t;
  7. while(t--)
  8. {
  9.     int n;
  10.     cin>>n;
  11.     int a[n][n];
  12.     for(int i=0;i<n;i++)
  13.     {
  14.         for(int j=0;j<n;j++)
  15.         {
  16.             cin>>a[i][j];
  17.         }
  18.     }
  19.     int i,k;
  20.         for(int j=0;j<n;j++)
  21.         {
  22.             i=0,k=j;
  23.             while(k>=0)
  24.             {
  25.                 cout<<a[i++][k--]<<" ";
  26.             }
  27.         }
  28.         int j;
  29.         for(i=1;i<n;i++)
  30.         {
  31.             j=n-1,k=i;
  32.             while(k<n)
  33.             {
  34.                 cout<<a[k++][j--]<<" ";
  35.             }
  36.         }
  37.         cout<<endl;
  38. }
  39. return 0;
  40. }

Here is the Video: