-1

I'm preparing for the Java OCA exam but there are several tricky questions about how iterates a multidimensional array. So, if I had this array and I wanted to iterate using the for and for-each loops what would all be ways to do it? I usually used only these three:

int [][]matrix = {{3,4,5},{6,7,8},{9},{10,11,12}};

//First way
for (int [] a : matrix){
 for (int i =0; i<a.length;i++){
   //code
 }
}

//Second way
for (int []a: matrix){
 for (int i: a){
   //code
 }
}

//Third way
for (int i = 0; i<matrix.length; i++) {
 for (int j=0; j<matrix[a].length; j++) {
  //code
 }
}

//Fourth way???

Thanks a lot!

Sam
  • 536
  • 5
  • 23
  • 4
    What exactly is your question? List-based answers "show me all ways to do xyz" are not too nice mostly. Do you have a use-case or something specific that is to be achieved? – Ben May 03 '18 at 11:08
  • 1
    Possible duplicate of [Ways to iterate over a list in Java](https://stackoverflow.com/questions/18410035/ways-to-iterate-over-a-list-in-java) – vincrichaud May 03 '18 at 11:13

1 Answers1

-2

You missed the for, foreach combination:

for (int i = 0; i<matrix.length; i++) {
  for (int j: matrix[i]){
    // code
  }
}

You can also use while loops instead of for. Can you be more specific about the context, so we can help you properly with what you need?

Nannan AV
  • 419
  • 7
  • 22
  • 2
    If you want clarifications by the person asking a question this should be done in the comments of the question - an answer should be given after all clarification was done so that it actually is an answer to the intended question :) – Ben May 03 '18 at 11:19