RYU5
RYU5

Reputation: 51

How can I express my for loop with a foreach loop on my 2D array?

public static boolean doit(int[][] a, int b){
    for(int i=0; i<a.length; i++){
        for (int j = 0; j < a[i].length; j++)
        {
            if(a[i][j] ==b) {
                return true;
            }
        }
    }
    return false;
}

So basically I want to use the ForEach loop, for checking if the array contains the int b, but I'm not sure how to use it.

public static boolean doitTwo(int[][] a, int b){
    for(c :a){
        for ( d:a){
              if(a[c][d] ==b) {
                return true;
            }
        }
    }

}

Upvotes: 0

Views: 43

Answers (1)

dpwr
dpwr

Reputation: 2812

Nearly there, but you're iterating over a in both loops when the inner loops should be using c. Also, when you are iterating over the values instead of the indexes like this, you don't need to index into the arrays (like you were doing with a[c][d]), as you already have the values in hand.

public static boolean doitTwo(int[][] a, int b){
    for(int[] c : a){
        for (int d : c){
              if(d ==b) {
                return true;
            }

    }

}

I also added types to your for loops, not strictly necessary as they can be inferred, but I prefer being explicit in Java.

The first for loop c : a takes a and iterates over its values. As it's a 2D array, each of it's elements are a 1D array! You then iterate over that 1D array and each values of the 1D array is int.

Example pseudocode:

# Original 2D array which is an array, containing arrays of ints. i.e. int[][]
x = [[1, 2, 3], [4, 5, 6];

for (a : x) {
  # at this point on the first iteration, a = [1,2,3]. i.e. int[]
  for (b : a) {
    # at this point on the first iteration, b = 1. i.e. int
  }
}

Upvotes: 1

Related Questions