2

Please, explain me step by step output of this code:

public class My {
    public static void main(String[] args) {
        int[] a = {1,2,3,4,1};
        for (int n : a) {
            a[n] = 0;
        }
        for (int n : a) {
            System.out.println(n);
        }
    }
}

I know that is an enhanced loop. But do not understand how it works with a[n]=0 Why this code outputs 00301?

2
  • It is best to take a piece of paper and do this yourself. For example the first element of the array is 1. The first iteration of the first for loop will set the value of the second element (with index 1) to zero. Commented May 1, 2018 at 10:47
  • @OP just to point out, the n in this case is iterated through the values stored in a, technically not iterated using a's index Commented May 1, 2018 at 11:24

3 Answers 3

3

You can debug this by adding a println statement:

    for (int n : a) {
        System.out.println("Changing element " + n + " of array from " + a[n] + " to 0");
        a[n] = 0;
    }

The output of this is:

Changing element 1 of array from 2 to 0
Changing element 0 of array from 1 to 0
Changing element 3 of array from 4 to 0
Changing element 0 of array from 0 to 0
Changing element 1 of array from 0 to 0
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!
0

This code is actually replacing value of nth index where n is the value assign to n while traversing

Comments

0

While iterating over the array a[], it changes the value of array. This is why a[2] and a[4] is never changed.

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.