F
F
Flasher2014-05-14 16:31:21
Java
Flasher, 2014-05-14 16:31:21

Java multidimensional array - how to explain string?

Wrote a code that works :)
But there was a question with a string in a nested loop.
Here is the whole working code:

public class Main{
  public static void main(String args[]){
    int a[][] = {{1,2,3,4,5,6},{1,2,3,4,5,6},{1,2,5,6},{1,2,3,4,5,6}};
    for(int i = 0; i < a.length; i++){
      for(int k = 0; k < a[i].length; k++){
        System.out.print(a[i][k]);
      }
    System.out.println("");
    }
  }
}

And here is the line that requires explanation
for(int k = 0; k < a[i].length; k++)
. It has k < number of columns (in theory, 1 cycle), and in the end it displays the entire array correctly. Explain why it works? :))

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey Vershinin, 2014-05-14
@WolfdalE

I can't understand what's confusing you. In the loop over i, we iterate over arrays - the elements of the array a. In a loop over k, we iterate over the elements of these same arrays. That is, we display the elements of all arrays in turn.

M
Maxim Moseychuk, 2014-05-14
@fshp

The loop runs as long as the condition is true. Your condition is written correctly, and it will be true until k < a[i].lengthAt the first iteration

k == 0
a[i].length == 6
What confused you?
UPD: the first cycle is lines (in the usual sense)
int a[][] = {
        {1,2,3,4,5,6},
        {1,2,3,4,5,6},
        {1,2,5,6},
        {1,2,3,4,5,6}
};

I think it's more visible.

S
smet4ik, 2014-05-14
@smet4ik

You mixed up rows and columns:
i/kk=0, k=1, .....
i=0 {1, 2, 3,4,5,6}
i=1 {1, 2, 3,4,5 ,6}
i=2 {1, 2, 5,6}
i=3 {1, 2, 3,4,5,6}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question