For loop extra increment

I can't wrap my head around why this code comes out to 13, as far as I can tell it should be 12.

1
2
3
4
5
6
int i, t[5];
for (i = 0; i < 5; i++)
	t[i] = 2 * i;
i = 0;
for (i = 0; i < 5; ++i)
	i += t[i];
Last edited on
I’m not sure what exactly you are trying to accomplish — you are using i for two different things. Don’t do that.

The reason you are getting 13 is because i = 8+4 = 12, ++i = 13, at which point the loop terminates because i >= 5.

To understand it, try to figure out what happens to i at each step through the loop on line 5.

Hope this helps.
Believe it or not i actually knew not to do that, but it's an example in a course I'm taking.

That said it's plenty of reinforcement on the reasoning not to... I think I managed to overthink it and apply the condition again at the end of the loop... Just for the increment? I'm not even sure, but I've got it now. Appreciate the help.
Sometimes I wonder what is going on in the heads of people who provide examples like that in programming courses...

Glad you got it. :O)
Topic archived. No new replies allowed.