Nub - 5 months ago 31

Java Question

Assume x is an integer and has been initialized to some value. Consider the code

`for (int a = 1; a < 20; a++)`

if (x < 0)

x = a;

Which statement will have the same effect on the value of x?

`if (x < 0) x = 1;`

`if (x < 20) x = 19;`

`if (x < 0) x = 19;`

`if (x < 20) x = 20;`

`x = 1;`

For this problem I was a little confused on what the question was asking because the answer was not what I was expecting. I chose answer choice

`if (x < 20) x = 19;`

`if (x < 0) x = 1;`

Answer

The answer is a. if `x`

is less than 0, then the loop will assign 1 to `x`

in the first iteration. The subsequent iterations will have no effect as x will be more than 0. if `x`

is already more than 0, then both approaches will not alter the value of `x`

.