Hartja
Hartja

Reputation: 57

Why does it skip array index 0?

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]?

Upvotes: 1

Views: 208

Answers (1)

Ben Green
Ben Green

Reputation: 438

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.

Upvotes: 3

Related Questions