Home java Infinite Cycle for in Java

Infinite Cycle for in Java

Author

Date

Category

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:

  1. First i = 0 .

  2. The value is calculated after the sign is equal. It is zero: result = i = 0 .

  3. postfix increment is calculated. Now i = i + 1 = 1 .

  4. The result of expression is written in I . As a result: i = result = 0 .


can be replaced by: i = ++ i . Then:

  1. First i = 0 .

  2. The prefix increment is calculated. Now i = i + 1 = 1 .

  3. The value is calculated after the sign is: result = i = 1 .

  4. 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

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions