L
L
Last_flower_of_hope2016-03-24 18:19:24
Java
Last_flower_of_hope, 2016-03-24 18:19:24

Loops without an integer in Java. How Does the Compiler Calculate?

// The body of the for loop can be empty
public class Empty3 {
public static void main(String args[]) {
int i;
int sum =0 ;
for(i = 1; i <= 5; sum+= i++);// There is no body in the loop
System.out.println("Sum: "+sum);
}
}
add with the value of the variable sum the result of summing the values ​​of the variables sum and i, and then increment the value of the variable i. Therefore, this operator is equivalent to the following sequence of operators.
sum = sum + i;
i++;
The answer would be: 15
How does the compiler calculate? Can't understand the text.
If sum =2//Then the answer is 17. How so? Help the fool!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2016-03-24
@Last_flower_of_hope

What do you not understand?
sum = 0+1+2+3+4+5=15

add the sum of the values ​​of the variables sum and i to the value of the variable sum, and then increment the value of the variable i.
repeat until i is greater than 5.

A
Artem Vereschaka, 2016-03-24
@And3en

This is basic knowledge.
for (^init^; ^condition^; ^expression^) { ^body^ }
The body can be thrown out like the rest of the parts.
^init^ is only executed once at the beginning of the loop.
In the following steps, at each pass of the loop, ^expression^ will be executed, then the validity of ^condition^ will be checked,
you can at least completely empty
for (;;);
will work ;)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question