1

Is it possible to get the index of a 2D array? Suppose I have the following array

int[][] arr = {{41, 44, 51, 71, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};

And I want to get the index of 88, how to do it?

1
  • do you mean like search for an element and return its index/indices? Commented Mar 4, 2012 at 12:56

4 Answers 4

4
for (int i = 0 ; i < size; i++)
    for(int j = 0 ; j < size ; j++)
    {
         if ( arr[i][j] == 88)
         {
              `save this 2 indexes`
              break;
         }
    }
Sign up to request clarification or add additional context in comments.

Comments

3

If they are not sorted, you will have to loop through all indexes [using double loop] and check if it is a match.

int[][] arr = {{41, 44, 51, 71, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
for (int i = 0; i < arr.length; i++) { 
    for (int j = 0; j < arr[i].length; j++) { 
        if (arr[i][j] == 88) { 
            System.out.println("i=" + i + " j=" + j);
        }
    }
}

will result in:

i=1 j=1
i=2 j=0

Comments

0

This is a primitive array, so it should be directly accessibly with the index:

int[] indexValue = arr[88];

EDIT:

Sorry, reading it again, if you mean the indices of the item 88 then there are multiple occurrences of 88 so you would need to iterate through each index and look for a match in each, and also have the size of the arrays stored somewhere. If it's possible and doesn't impact on performance, use an ArrayList or Vector and store Integers objects instead.

1 Comment

this is a 2d array, arr[88] is a int[]. Also, it returns the element in index 88, and not the index of element 88 [which I think is what the OP is after]
0
System.out.println(Arrays.toString(da(arr,88)));

    }
    static int[] da(int dt[][],int target){
        for(int i=0;i<dt.length;i++){
            for (int j = 0; j <dt[i].length ; j++) {
                if(dt[i][j]==target){
                    return new int[]{i,j};
                }

            }
        }
        return new int[]{-1,-1};
    }
}

Comments

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.