# first itteration of "for" statement acts differntly to all the rest, why?

• March 1st, 2011, 09:25 AM
SPACE MONKEY
first itteration of "for" statement acts differntly to all the rest, why?
Dear All I have the following code and it works, just trying to understand the results.
Code Java:

```public class Counter { public static void main(String[] args) { int value1 = 7; for (int i = 2, sum = 0; i <= value1; i += i, sum = i) { System.out.println("Sum = " + sum + " i = " + i ); }}}```
OUTPUT OF CODE:
Sum = 0 i = 2
Sum = 4 i = 4

QUESTION
So why, on the first go around of the "for" statement, is "sum" not equal to 2?

If the third part of the "for" statement(; i += i, sum = i) is being ignored in the first iteration of the loop, the results I see make sense?

This also makes sense, because the first part of the "for" statement is being ignored after the first iteration of the "for" loop, otherwise "sum" and "i" would be set back to there original values.

SECOND QUESTION:
Am I correct in my assumptions?

SPACE MONKEY:confused:
• March 1st, 2011, 09:39 AM
KevinWorkman
Re: first itteration of "for" statement acts differntly to all the rest, why?
What is value1 supposed to be? Better yet, post an SSCCE that we can copy and paste to play with.
• March 1st, 2011, 09:44 AM
SPACE MONKEY
Re: first itteration of "for" statement acts differntly to all the rest, why?
Dear KevinWorkman:

Sorry "value1" has been set, it is there to set the upper limit for "i", to indicate when the "for" statement should stop running.

I made it so I could set "value1" to different values. I have turned "value1" into a fixed value as it is not integral to the question I have posed.
• March 1st, 2011, 09:48 AM
KevinWorkman
Re: first itteration of "for" statement acts differntly to all the rest, why?
Quote:

Originally Posted by SPACE MONKEY
So why, on the first go around of the "for" statement, is "sum" not equal to 2.

The answer to that question is because "the third part" (the increment expression) of the loop executes after each iteration of the loop, not before.

Recommended reading: The for Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)

I'd also recommend you step through this with a debugger. That will make it pretty obvious what's going on.
• March 1st, 2011, 10:06 AM
SPACE MONKEY
Re: first itteration of "for" statement acts differntly to all the rest, why?
Dear KevinWorkman:

Thanks. I will use the tutorials first next time.
I can not find the way to mark the post as completed, or answered. That option only appears in the initial post and not afterwords.