SummerBoy
SummerBoy

Reputation: 125

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];

Upvotes: 0

Views: 64

Answers (4)

BFunk
BFunk

Reputation: 377

This is what your array values looks like after the loop runs with the indexs underneath:

[0][1][3][6][10]
 0  1  2  3  4

So when the loop gets to i=3 like this:

values[3] = 3 + values[3-1];

its the same as saying

values[3] = 3 + 3 

since the value of values at index 2 is 3

Upvotes: 0

MordechayS
MordechayS

Reputation: 1546

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.

Upvotes: 3

Muazzam khan
Muazzam khan

Reputation: 18

int[] values = new int[5];

<===== At this index 5 value is 6 (0,1,2,3,4,5)

the index's are six because index start from 0;

Upvotes: -2

Henry
Henry

Reputation: 43738

The following assignments are made:

values[1] = 1 + 0 (= 1)
values[2] = 2 + 1 (= 3)
values[3] = 3 + 3 (= 6)
...

So the value[3] is indeed 6.

Upvotes: 3

Related Questions