ihoaxed - 1 year ago 109
Java Question

# Rewrite the following code to have the arithmetic performed only once, even if the loop executes 1,000 times?

So I'm reading a programming book and it had this question written:

How could you rewrite the following code to have the arithmetic
performed only once, even if the loop executes 1,000 times?

`while (x < a + b)`

`// loop body`

``````int sum = a + b;
while(x < sum)
// loop body
``````

I'm really not understanding the logic here....Can someone explain this answer to me? Because this doesn't make sense to me at all.

In the first version of the loop:

``````while (x < a + b)
// loop body
``````

The sum `a + b` is calculated during each iteration of the loop. If the sum is independent of the loop and never changes, then this is wasteful. So one option for efficiency is to compute this sum outside the loop as in the second version:

``````int sum = a + b;
while(x < sum)
// loop body
``````

I would expect that a good Java or C compiler would be able to detect this on its own, and make this optimization automatically.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download