0

When iterating through array x with an enhanced for loop what do y and z represent and how does the loop work. Here is the code I have written, it works but I don't understand exactly why and how it works. If someone could explain the syntax of the for loop when displaying a multidimensional array I would appreciate it.

// enhanced for loop
String[][] x =
{
    {"a", "a^2", "a^3"},
    {"1", "1", "1"},
    {"2", "4", "8"},
    {"3", "9", "27"},
    {"4", "16", "64"}    
};

for (String[] y: x)
{
    for (String z: y)
    {
        System.out.print(z + "\t");
    }
    System.out.println();
Aaron
  • 15
  • 1
  • 4
  • Do you have an instructor to whom you can redirect these tutorial type questions? – MarsAtomic Sep 22 '14 at 20:01
  • 1
    I would start out with the basic for loop. If you can understand this tutorial: http://www.homeandlearn.co.uk/java/multi-dimensional_arrays.html then move on to the enhanced for loop: https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with, which after understanding how the enhanced for loop works, you should have no problem linking the concept of multidimensional arrays with enhanced for. – scrappedcola Sep 22 '14 at 20:18
  • possible duplicate of [How does the Java for each loop work?](http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work) – Kumar Abhinav Sep 22 '14 at 20:18

4 Answers4

1

An enhanced for loop over an array is equivalent to iterating over the indices of the array in a regular for loop :

for (int i=0; i<x.length; i++)
{
    String[] y = x[i];
    for (int j=0; j<y.length; j++)
    {
        String z = y[j];
        System.out.print(z + "\t");
    }
    System.out.println();
}

When you are iterating over a two dimentional array, each element of the outer array, is itself an array.

Eran
  • 387,369
  • 54
  • 702
  • 768
1
for (String[] y: x)

Means 'for each String array (Called y) in the array of arrays (Called x)'.

So y[0], for example is {"a", "a^2", "a^3"}

Then similarly, for (String z: y) means 'for each String called z in the String array we previously defined as y.

So z[0] at the first pass of y is "a". Then z[1] is "a^2" and z[2] is "a^3".

This completes the iteration of the first entry of y, and we repeat with the next one, etc, etc.

ne1410s
  • 6,864
  • 6
  • 55
  • 61
0

what s happening is your by your first for (String[] y: x)your going through each element in the x, those happen to be of type String[], arrays of strings, and for each one of theme you iterate over its element by the second loop for (String z: y), and thus y would be : ("a", "a^2", "a^3"), ("1", "1", "1"), ("2", "4", "8"), . . and values for z would be a, a^2, a^3, 1 ....

TheFuquan
  • 1,737
  • 16
  • 18
0

You could conceptually think of a 2D array to be an array of arrays. Each element of level 1 array stores reference to another array and each element of level 2 array is the actual data, in this case, an 'int'.

SammarZ
  • 11
  • 3