+ 3
For loop ++i same as i++? Why code no work? Help!
for(i=0;i<3;i++) document.write(i); //outputs012 for(i=0;i<3;++i) document.write(i); //outputs012 Why both output 012? Shouldn't ++i make the i increase before the assignment? Shouldn't the second for loop be outputting only 12 instead of 012? I'm confused. How does it work? https://code.sololearn.com/W7z1ISEDY220/?ref=app
5 Answers
+ 4
Muhd Khairul Amirin Bin Yaacob is right, there is no difference here. You probably think of something like this:
i++ < 3 or ++i < 3.
Here it would matter because in the first case i < 3 would be checked, while in the second case i+1 < 3 would be checked. However, this is not how it works.
Think of the loop like:
comparison (i < 3)
loop body is executed
increment (++i)
Because it is a standalone statement, it will always be checked if i < 3.
Note: You are suggested to use ++i, the pre-incrementation, though, since it is slightly more efficient than i++, because of the way it is implemented in the language.
+ 4
i++ and ++i in a loop is same. They have no difference
+ 3
Thanks you all.
+ 2
Try the following to see the difference:
for(i=0;i++<3;)
document.write(i);
for(i=0;++i<3;)
document.write(i);
+ 1
In JS it's same in the loop. For C++ it's about speed and slightly different.