• Post Reply Bookmark Topic Watch Topic
  • New Topic

Increment operators in a "for" loop  RSS feed

 
Derek Harper
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a question concerning the following program:


class ForDemo {
public static void main(String[]args) {

int i;
for(i = 0; i < 5; i++)
i = ++i + ++i;
System.out.println(i);
}
}

After compiling and running the program, the output is '12'. Is this due to the fact that after the loop is finished, i has the value of 5 and the pre increment operators increase the values of both "i"s to 6? ( i = ++i + ++i)

i = 6 + 6
i = 12

Am i accurate on this explanation? Thanks in advance.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. I think you can see what happens if you put a System.out.println inside the loop. Basically, what happens is :
First loop : i = 1 + 2 = 3 (next loop, i++, i = 4)
Second loop : i = 5 + 6 = 11 (next loop, i++, i = 12)
[ March 27, 2008: Message edited by: Christophe Verre ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
http://faq.javaranch.com/java/PostIncrementOperatorAndAssignment
 
Derek Harper
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the assistance guys.....

I think i follow you now. When starting out, i = 0, it goes through the loop, the condition is checked (true), and it is then passed into the value of 'i':

i = ++0(1) + ++1(2) <------- becomes 2 after 1st increment
i = 3

The value becomes 3 and then it has to be incremented (i++, i = 4). Going thru the loop again, i = 4 and the condition is checked (true), and it is then passed into the value of 'i':

i = ++4(5) + ++5(6) <------- becomes 6 after 1st increment
i = 11

The value becomes 11 and then it has to be incremented once more (i++, i = 12).


Is this accurate now?
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Derek Harper:
Is this accurate now?
It looks right. Try changing your loop to read like this:Then see what happens and that ought to confirm your suspicions.
 
Derek Harper
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aha!!!

Yep, that did it. Thanks Campbell.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!