Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+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 (1 point)

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 (1 point)
+2

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

+6 votes

The answer is
i=4
j=2
k=1

answered by (1 point)
+3

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

+4

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

+4

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

+3

Oh, I got it! Thank you so much!

...