Pre- vs Post-Increment
Mediumjava
Read an integer x. Simulate both forms of increment starting from x and print what each produces.
- Post-increment:
r1 = a++—r1gets the old value, thenabecomesx + 1. - Pre-increment:
r2 = ++b—bbecomesx + 1first, thenr2gets the new value.
Input: one integer x.
Output: two lines:
<r1> <a>
<r2> <b>Example 1
Input
5
Output
5 6 6 6
- -1000000 <= x <= 1000000
Hint 1
a++ returns the value of a before adding 1; a is then x + 1.
Hint 2
++b adds 1 to b first, so both r2 and b are x + 1.
Post-increment (a++) evaluates to the old value, so r1 equals x while a moves to x+1. Pre-increment (++b) updates first, so both r2 and b are x+1. This is the classic difference the topic highlights.