- 1

In the code: for(x=1; x<=5; x++) { system.out.printIn(x); } ++x and x++ has no difference in the output ... why?

13th Mar 2017, 8:51 AM
Karuna Kukreja
Karuna Kukreja - avatar
3 Answers
+ 1
Because the increment of x is done at the end of the block, so is blase x++ or ++x
13th Mar 2017, 9:35 AM
FMC Drummer
FMC Drummer - avatar
0
for(a, b, c) a is executed the first time the loop is run b is checked at the start of each loop run c is executed at the end of each loop run which means that in this case the first time x is set to 1 then checks that 1<=5 is true then prints 1 if c is ++x ----> x is set to 2 if c is x++ ----> x is also set to 2 then checks 2<=5 is true prints 2 ... in this way the example above gives the same result whether you use x++ or ++x
13th Mar 2017, 9:41 AM
elhuus
0
When you iterate using x++ and ++x inside the for loop syntax, first the condition is tested and code is executed once for initial declaration of x which in this case is x =1. After one loop, then the iteration comes into picture which will have the same effect for x++ and ++x inside the for loop syntax. If you want to see the difference between the two, do the iteration part in the System.out.println(x++); and System.out.println(++x); instead of doing it inside the for loop syntax. Try these two: for(x=1; x<=5;) { System.out.println(x++); } and for(x=1; x<=5;) { System.out.println(++x); }
13th Mar 2017, 9:42 AM
Hitesh Kaku
Hitesh Kaku - avatar