1

Is foreach for loop is only for one dimensional array? if not please explain how can i change the for loop in enhanced or foreach loop in the code below

class Kevil{
public static void main(String[] args){

    int[][] num={{1,2,3,4,5,6,7,8,9,10},{11,12,13,14,15,16,17,18,19,20},{21,22,23,24,25,26,27,28,29,30}};

    for(int i = 0;i<num.length;i++) {
        for(int j =0 ;j<num[i].length;j++){
            System.out.print(num[i][j]);
            System.out.print(" ");
        }
        System.out.print("\n");
    }

}
}

2 Answers 2

2

Each element of your num array is an int array itself. If you want a for-each loop you will have to use int[] as a type for the loop variable.

class Kevil{
public static void main(String[] args){

int[][] num={{1,2,3,4,5,6,7,8,9,10},{11,12,13,14,15,16,17,18,19,20},{21,22,23,24,25,26,27,28,29,30}};

for(int[] i : num) {
    for(int j : i){
        System.out.print(j);
        System.out.print(" ");
    }
    System.out.print("\n");
}

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

Comments

0

like so?

for(int[] row : num){
   for(int element : row){
     //do something with element
   }
}

Comments

Your Answer

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