+ 4

Tell me why does this print 1 instead of 0?

int sum = 0,bum = 0; for(int i = 1;i <= 5;++i) { sum += i; System.out.println(i); } for(int i = 1;i <= 5;i++) { bum += i; System.out.println(i); } if(sum == bum) { System.out.println("1"); } else { System.out.println("0"); } How does I++ and ++I work here?.

11th Sep 2017, 9:01 PM
Mark Daniel Walker
Mark Daniel Walker - avatar
3 Respostas
+ 3
because both conditions (a.k.a finish line) are : less than or equal to 5 , which is : 1+2+3+4+5 at the end of both sum or bum. regardless the plus-ing step , same finish line : ++i or i++ , different only seen in specific condition. try this too : int i,j; i=0; j=0; System.out.println(i); System.out.println(++i); if(i==0)System.out.println("ouch"); System.out.println(j); System.out.println(j++); if(j==0)System.out.println("LoL"); hope helps.
11th Sep 2017, 9:31 PM
Mikhael Anthony
Mikhael Anthony - avatar
+ 1
so, you want to say that it doesnt really do anything different in this case?
11th Sep 2017, 9:24 PM
Mark Daniel Walker
Mark Daniel Walker - avatar
0
Difference between ++i and i++ matters only if used in a same instruction. For example if(1>i++) is not same than if(1>++i).
11th Sep 2017, 9:20 PM
Toctor
Toctor - avatar