Skip to content
Advertisement

Java Arrays/Loops

Hi i saw this question online and i was trying to solve it but i just could not understand how the answered was determined.

int[] n = {0, 1, 0, -1};

for (int i = 1; i < n.length; i++) {
    if (n[i] == 0 && n[i - 1] != 0) {
        int x = n[i - 1];
        n[i - 1] = n[i];
        n[i] = x;               
    }        
}
System.out.println(n[2]);

The answer is 1 which i have no idea how or why is it 1. Wonder if anyone is kind enough to explain why is the answer 1.

Advertisement

Answer

The code block inside the if swaps the two numbers in n[i] and n[i - 1].

The if itself (The condition) checks if the n[i] is zero and n[i - 1] is non-zero.

The loop runs over all i values from 1 to the end of the array.

Let’s follow the loop run, shall we? (row numbers are i value)

  1. n[1] is 1, n[0] is 0 – condition false and if block not entered.
  2. n[2] is 0, n[1] is 1 – condition true and if block entered. Now n[2] is 1, n[1] is 0.
  3. n[3] is -1, n[2] is 1 – condition false and if block not entered.

End of array.

So n[2] is 1.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement