Problems
1. Operators
Why both print same values?
for (i = 0;i<10;i++) {
System.out.print(i);
}
System.out.println();
for (i=0;i<10;++i) {
System.out.print(i);
}
// 0123456789
// 0123456789Both i++ and ++i increment the value of i by 1, but the difference lies in when the increment happens in expressions — not in loops like for where the value isn't used during increment.
i++→ Post-increment: Incrementsiafter the value is used++i→ Pre-increment: Incrementsibefore the value is used
But in a for loop:
for (i = 0; i < 10; i++) // or ++iThe increment expression (i++ or ++i) happens after each iteration, and its return value is not used anywhere in the loop control itself.
So both loops behave the same:
Initialize
i = 0Check condition
i < 10Execute
System.out.print(i)Increment
i(post or pre — doesn’t matter because value isn't used)Repeat
If we wrote something like:
Here, the difference matters:
x = i++: assigns the value ofitox, then incrementsiy = ++i: incrementsi, then assigns the new value toy
Last updated