Nub Nub - 1 year ago 66
Java Question

How to solve for x when observing through a for loop

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 b.
if (x < 20) x = 19;
because 19 is less than 20 and the other answer choices are false when plugging into 'x'. The answer to this question is actually a.
if (x < 0) x = 1;
. I am confused on why answer choice a. is the answer.

Lew Lew
Answer Source

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.

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