0

Why is the output 0 2 2 4 4 for this for loop?

for (int = 0; i < 6 ; i ++){ System.out.println(i); System.out.println(i++); }

9th Sep 2017, 1:03 AM
Kajal
2 Answers
+ 10
I'm guessing that this is just a typo, but i is not assigned in the initialization section of your for loop. Once that is fixed and the for loop is ran the output should be: 0 0 2 2 4 4 not 0 2 2 4 4 I'm also going to guess that your problem is the understanding of i++ and what is happening with: System.out.println(i++); i++ (postfix) will use the current value of the variable i and then increment the value. So i is output, then incremented, then i is incremented once again in the incrementation section of the for loop. If the prefix incrementation (++i) were used instead then the value of i would be incremented first and then output. resulting in: 0 1 2 3 4 5
9th Sep 2017, 1:15 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
Thank you so much for the explanation. I get it now! And sorry you had to navigate through the various mistakes I made in posting the question
9th Sep 2017, 1:25 AM
Kajal