Doubt in 2d array

#include
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
int k=0,l=0;
int mat[n][m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
cin>>mat[i][j];
}
for(int x=0;x<n*m;x++)
{

    cout<<mat[k++][l]<<", ";
     if(k-1==n-1)
    {
        k=0;l=l+1;
    }
   
}
cout<<"END"<<endl;

return 0;

}
input:
4 4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44
output:
11, 21, 31, 41, 42, 32, 22, 12, 13, 23, 33, 43, 44, 34, 24, 14, END
what’s wrong with the code,it was only able to pass one testcase

Hi @dare_devil_007
See the output you are getting is not as per the question requirement. For example for input as :

4 4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44

Your code is printing output as 11, 21, 31, 41, 12, 22, 32, 42, 13, 23, 33, 43, 14, 24, 34, 44, END
But the correct output is 11, 21, 31, 41, 42, 32, 22, 12, 13, 23, 33, 43, 44, 34, 24, 14, END

So for getting the desired output what you need to do is that run two loop for i and j and there if j%2==0 then you have to print column from top to bottom and else print it from bottom to top.

Here is your corrected code :

1 Like

Hi @dare_devil_007
Mark your doubt as resolved if you get what was wrong with you code.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.