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();
3

4 Answers 4

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.

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

Comments

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.

Comments

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 ....

Comments

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'.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.