Difference between pre increment and post increment in for loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Difference between pre increment and post increment in for loop

Is there is any difference between following two for loops For(int i =0;i<5;i++) System.out.println(i); AND For(int i=0;i<5;++i) System.out.println(i); If any state with description

31st Mar 2018, 1:13 PM
Ankush jaswal
Ankush jaswal - avatar
7 Answers
+ 15
Muhammad Khairul Amirin Bin Yaacob both will have 01234 output In loop post - pre increment will not make any difference
31st Mar 2018, 1:21 PM
🌛DT🌜
🌛DT🌜 - avatar
31st Mar 2018, 1:17 PM
🌛DT🌜
🌛DT🌜 - avatar
+ 6
1. for (int i=0;i<5;i++) output: 01234 2 for (int i=0;i<5;++i) output: 12345??
31st Mar 2018, 1:16 PM
Muhd Khairul Amirin
Muhd Khairul Amirin - avatar
+ 1
Gordie nice post. Thank you.
31st Mar 2018, 5:51 PM
Alex
Alex - avatar
0
Muhammad Khairul Amirin Bin Yaacob That's wrong. The incremention isn't used directly and therefore it doesn't matter if you use ++i or i++. Pre- and postincrement only differs when you pass it to something while incrementing it. However: it's better to use pre increment, because post increment is more costly. Pre increment directly returns the incremented value, but post increments need to copy the value in a temporary variable, increment the original and then returns the previous made copy.
31st Mar 2018, 1:57 PM
Alex
Alex - avatar
0
Question: how would your answer apply to overloaded increment operators for an object? In case the answer is no: would it be bad practice to even implement post increment in a costly class?
31st Mar 2018, 6:02 PM
Alex
Alex - avatar
0
pre increment increase the number before and then proceed but post increment proceed the value before and then increase
1st Apr 2018, 5:13 AM
Kalyan Chauhan