0

Java - Can you please explain this code?

public class P17 { public static void main(String[] args) { int[] v = { 1, 2, 3, 4 }; print(v); fiddle(v, v[2] - 1); print(v); fiddle(v, v[2] - 1); print(v); } public static void fiddle(int[] array, int idx) { array[idx] = array[idx - 1] + 2; } public static void print(int[] array) { System.out.print(array[0]); for (int i = 1; i < array.length; i++) System.out.print(", " + array[i]); System.out.println(); } }

10th Aug 2018, 2:16 PM
Magda
3 Answers
+ 2
Array (original values) index |0 |1 |2 |3| value |1 |2 |3 |4| * First call to fiddle: fiddle(v, v[2] - 1) Knowing v[2] = 3 we know v[2] - 1 = 2 So we''ll pass 2 as idx argument to fiddle * Inside fiddle (remember idx = 2) array[idx] = array[idx - 1] + 2; v[2] = v[1] + 2 meaning v[2] = 2 + 2 v[2] = 4 ==================================== Array (values modified by first call) index |0 |1 |2 |3| value |1 |2 |4 |4| * Second call to fiddle: fiddle(v, v[2] - 1) Knowing v[2] = 4 we know v[2] - 1 = 3 So we''ll pass 3 as idx argument to fiddle * Inside fiddle (remember idx = 3) array[idx] = array[idx - 1] + 2; v[3] = v[2] + 2 meaning v[2] = 4 + 2 v[3] = 6 Hth, cmiiw
10th Aug 2018, 5:37 PM
Ipang
+ 2
You're welcome! glad if it helps : )
10th Aug 2018, 8:24 PM
Ipang
+ 1
Thank you for explanation, I truly appreciate your help!
10th Aug 2018, 8:23 PM
Magda