+ 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 } }

14th Mar 2022, 4:18 PM
Mihyeon Yi
4 odpowiedzi
+ 8
Mihyeon Yi first inside works then outside. So a[1] = 2 Now a[a[2]] a[2] = 3 Now a[3] = 4
14th Mar 2022, 4:25 PM
A͢J
A͢J - avatar
+ 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?
14th Mar 2022, 4:26 PM
Abhishek Tandon
Abhishek Tandon - avatar
+ 5
OK thanks guys for opening my eyes!
14th Mar 2022, 4:29 PM
Mihyeon Yi
+ 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..
14th Mar 2022, 4:28 PM
Jayakrishna 🇮🇳