Why with this construction of the for cycle, it turns out endless zeros output?
int i;
for (i = 0; i & lt; 10; i = i ++) {
System.out.printLN (I);
}
Answer 1, Authority 100%
Your expression: i = i ++ . What happens here in steps:
-
First
i = 0. -
The value is calculated after the sign is equal. It is zero:
result = i = 0. -
postfix increment is calculated. Now
i = i + 1 = 1. -
The result of expression is written in
I. As a result:i = result = 0.
can be replaced by: i = ++ i . Then:
-
First
i = 0. -
The prefix increment is calculated. Now
i = i + 1 = 1. -
The value is calculated after the sign is:
result = i = 1. -
The result of expression is written in
I. As a result:i = result = 1.
In general, the postfix increment in the assignment operator over the same variable does not make anything useful. From here and your infinite cycle.
Answer 2, Authority 23%
I ++ Operator There is a brief entry i = i + 1 . But there is a version of writing ++ I or I ++ .
The difference is when the increment operation occurs before turning to the variable or after. In your case, first the value i is assigned to the variable i , and then the increment occurs, but its value is not saved.
Now if you write ++ I , then everything will work as it should work.
Answer 3, Authority 15%
It is necessary to correct in the last value of the cycle parameters on:
for (int i = 0; i & lt; 10; i ++) {
System.out.printLN (I);
}
In your case, after each iteration of the cycle, you are assigned i = 0 (as ++ happens after the assignment), and the cycle again processes i = 0