+ 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

7th Jun 2018, 1:35 PM
Andre Daniel
Andre Daniel - avatar
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.
7th Jun 2018, 2:22 PM
Shadow
Shadow - avatar
+ 4
i++ and ++i in a loop is same. They have no difference
7th Jun 2018, 1:38 PM
Muhd Khairul Amirin
Muhd Khairul Amirin - avatar
+ 3
Thanks you all.
7th Jun 2018, 3:59 PM
Andre Daniel
Andre Daniel - avatar
+ 2
Try the following to see the difference: for(i=0;i++<3;) document.write(i); for(i=0;++i<3;) document.write(i);
15th Jun 2018, 4:39 AM
ŠœŠøŠŗŠ¾Š»Š° Š¤ŠµŠ“Š¾ŃŃ”Ń”Š²
ŠœŠøŠŗŠ¾Š»Š° Š¤ŠµŠ“Š¾ŃŃ”Ń”Š² - avatar
+ 1
In JS it's same in the loop. For C++ it's about speed and slightly different.
17th Jun 2018, 8:09 PM
Š”ŠµŃ€Š³ŠµŠ¹ Š“Ń€Š°Š“Š¾Š²Šøч
Š”ŠµŃ€Š³ŠµŠ¹ Š“Ń€Š°Š“Š¾Š²Šøч - avatar