FlyingMonkey FlyingMonkey - 1 month ago 8
Java Question

Understanding for loops and array indexes

I want to know why in this example value[3] is 6 and not 5.

When i = 3, shouldn't value[i] which is 3 be added to 2 (3-1) to give 5?

int[] values = new int[5];
for (int i = 1; i < 5; i++)
values[i] = i + values[i-1];

Answer

First, read about default values. As written there, the int type's default value is 0.

So, When you initialize your int array in the first line:

   int[] values = new int[5];

You create an array of size 5, which holds zero values by-default: values = {0,0,0,0,0}.

Now, lets move on to the iterations in-hand:

  • When i = 1: values[1] = 1 + values[0] (Which is initialized with a default int value of 0, as explained) = 1.
  • When i = 2: values[2] = 2 + values[1] = 2 + 1 = 3.
  • When i = 3: values[3] = 3 + values[2] = 3 + 3 = 6.
Comments