0

problem

i/o formats

sample test case

For a given two-dimensional integer array/list of size (N x M), print the array/list in a sine wave order, i.e, print the first column top to bottom, next column bottom to top and so on.

I am unable to get the expected output for this problem. Please find my code below:

#include <bits/stdc++.h>
using namespace std;

void wavePrint(int input[][2], int nRows, int mCols)
{
    //Write your code here
    for(int i=0;i<mCols;i++){
        int j=0;
        for(;j<nRows;j++){
            cout<<input[j][i]<<" ";
        }
        i++;
        for(;j>=0;j--){
            cout<<input[j][i]<<" ";
        }
    }
}




int main()
{
    
        int input[][2]={{5,6},{2,4}};
        wavePrint(input, 2, 2);
        cout << endl;
    
}
2
  • 2
    Yes, the shown algorithm is completely wrong. Hint: write out, on paper, a very small matrix, 4x4. The matrix originally contains numbers 1 through 16 in consecutive order. Now, write out what the resulting algorithm specifies the output should be, in a 2nd matrix. Now compute, from the output, the coordinates of each cell in the 2nd matrix that comes from the first matrix. Write those coordinates in a third matrix. Now stare at the third matrix, and see what the real pattern is, and then the problem with the shown code becomes obvious. Commented Jul 31, 2022 at 14:05
  • Along with algorithm, you forgot to decrement j in your current program, resulting in printing garbage value. Commented Jul 31, 2022 at 14:12

1 Answer 1

0

Since I do not have enough reputation to comment, the only thing I can do is answer.

Your primary issue is that you are incrementing the i loop index inside the loop. You don't need to/want to do this.

Walk through your code and track the variable values on each line (or use a debugger to do this) and you will see what the output looks like and where you've gone wrong.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.