Welcome to the CSC Q&A.
Get help and give help!
Write great code!
It is our choices... that show what we truly are, far more than our abilities.


+16 votes

What are the values of i, j, and k after the following code statements?
int i = 2;
int j = 3;
int k = 4;
int x = i + j + k;
i = x - i - j;
j = x - j - k;
k = x - i - k;

asked in CSC211_Winter2018 by (8 points)

2 Answers

+7 votes

Rather than creating one big equation to define “k” at the end I suggest that you just do the computation in order, just as the computer would. So it would be “x” which, when it is defined, is 9, minus “i” which was 2 but has been redefined to be “x-i-j”, so when the final “k” is computed, “i” is 4, and then minus “k” which during the final defining of “k” it is 4. Therefore, the output of “k” is (9 - 4 - 4 = 1).

When in doubt, try to think through it like the computer would.

Hope this cleared it up.

answered by (8 points)

That clears a lot of confusion for me. Thank you so much!

+6 votes

The answer is

answered by (8 points)

I mean I cannot find k=1 since since k = (i + j + k) - i - k = j, and the value of j is 2?


Sorry, k=1 because when Java read the order, it used the old x (before i changed) so you have to use the old x to find k


k=2 if there is another statement x=i+j+k (before k=x-i-k) to give x a new value


Oh, I got it! Thank you so much!