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(); } }
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
+ 2
You're welcome! glad if it helps : )
+ 1
Thank you for explanation, I truly appreciate your help!