1

Say for example I had the following:

    int[][] courses = {
            {1, 0},
            {2, 0},
            {3, 1},
            {3, 2},
    };

Now don't the first index represents x, and second index represents y? For example, courses[x][y], so courses[0][1], should print 2, but actually prints 0, why is that?

2
  • Because x=0 is the first index, so it gets the {1,0} , then y=1 is the second index and that gets you the 0. Commented Dec 11, 2016 at 6:59
  • You should declare your array as {{1,2,3,3},{0,0,1,2}} Commented Dec 11, 2016 at 6:59

2 Answers 2

3

A 2D array is actually an array whose elements are arrays.

The first index of the array is the index of the outer-most array.

Therefore courses[0] returns the inner array {1, 0} (the first element of the outer array) and courses[0][1] returns the second element of that array, which is 0.

courses[1][0] would return 2.

Now don't the first index represents x, and second index represents y

If you treat a 2D array as a matrix, and by x you mean column index and by y you mean row index, then actually it's the other way around - the first index is the row index (y) and the second index is the column index (x).

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

Comments

0

courses[0,0]=1 courses[0,1]=0 - this is the first row

courses[1,0]=2 courses[1,1]=0 - this is the second row

courses[2,0]=3 courses[2,1]=1 - this is the third row

Comments

Your Answer

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