+ 2
Why does accessing array with the accessing array as an index work?
Why does accessing array with the accessing array as an index work? This code is from the sololearn challenge. It works fine and I don't know why. public class Main { public static void main(String[] args){ int[] a = {1,2, 3, 4, 5}; System.out.print(a[a[a[1]]]); //Outputs 4 } }
4 Respuestas
+ 8
Mihyeon Yi
first inside works then outside.
So a[1] = 2
Now a[a[2]]
a[2] = 3
Now a[3] = 4
+ 5
Why should it not?
Forget programming syntax for some time, what do you think of this:
Suppose f(x) = x + 2
y = f(f(x)))
= f(x + 2)
= (x + 2) + 2
= x + 4
Sounds familiar?
+ 5
OK thanks guys for opening my eyes!
+ 4
Its not accessing array with accessing array..
Since you know that a[I] returns value at index I. Then a[ a[ a[1] ] ]
inner a[1] returns 2 then it's the index to a as a[2] returns 3 finally a[3] returns 4
a[ a[ a[1] ] ] => a[ a[2] ] => a[ 3 ] => 4
hope it helps..