1

I came across this computer science problem and it wasn't working out the way I was writing it down. This is the code:

int[][]grid = {{1,2,3,4},{5,6,7},{8,9},{10}};

    for(int i = 0; i < grid.length; i++)
        for(int j = 0; j < grid[i].length; j++)
            grid[j][i] = grid[i][j];
    System.out.println(Arrays.toString(grid[1]));

It should change grid[0] to {1, 5, 8, 10} but instead it does nothing to it. Why does it skip over that one? Shouldn't i start out as 0 so the second for loop should start with grid[0][0] = grid[0][0] then grid[1][0] = grid[0][1]?

1
  • 2
    To change grid[0] to {1,5,8,10} you should do grid[i][j] = grid[j][i]; Commented Apr 22, 2016 at 8:22

1 Answer 1

3

It's because you're changing the initial variable (grid) on each iteration, put the output into a separate variable and then print that.

Explanation:

grid = {{1,2,3,4},{5,6,7},{8,9},{10}};

After the first sub loop (looping j)

grid = {{1,2,3,4},{2,6,7},{3,9},{4}};

Then when it performs the subsequent i loops, you can see it puts the numbers back where they were. If you start with an empty array as your output variable, you will avoid this problem.

Sign up to request clarification or add additional context in comments.

1 Comment

obviously if required for any reason, after the processing of the loops is complete, you can assign the output variable content back into the input variable (grid)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.