217,250 views
14 votes
14 votes
What is the output of the following program? (Show your work)

int x = 3, y = 2;
System.out.println("x = " + y);

x = 5 + y * 7 % 3;


y = x - y * x - 3 / 2;


System.out.println("x = " + x);
System.out.println("y = " + y);

User Tryx
by
2.5k points

1 Answer

16 votes
16 votes

Answer:

x = 2

x = 7

y = -8

Step-by-step explanation:

int x = 3; (here the variable of type int called x is declared and given the value 3)

int y = 2; (here another variable of type int called y is declared and given the value 2;

System.out.println("x = " +y ); (this instruction will print the value of y in the console terminal but deceivingly saying that the value belongs to x variable. So whoever reads will read "x = 2" instead of "x = 3" which would be the correct value associated with x.

x = 5 + y * 7 % 3; (here the value of x is changed from 3 to 5 + y * 7 % 3. What this means is that the first value of y (2) is multiplied by 7 and then get the mod of division 14 / 3 which is 2. Then added to 5. So the final result is 7 which is now the new value of x)

y = x - y * x - 3 / 2 (same as the above but for the value of y: here - 2 is multiplied by 7 and - 3 is divided by 2. Now we have 7 - 14 - 1.5 which is -8.5 but since you specified the variable type was an int and not double or float, then the program ignores significant numbers, so it ignores the .5 or whatever comes after the point instead of rounding it. PS: [So for instance if the result was 8.9, the value printed would be 8])

System.out.println("x = " + x); (prints the new value of x but this time it does not deceive the reader)

System.out.println("y = " + y); (prints the new value of y, and the letter y is shown in the screen for the first time with the correct value associated)

User Martin Omander
by
3.1k points