What will be the values of ans, x, and y after the following statements are executed? int ans = 35, x = 50, y =50; if ( x >= y) { ans = x + 10; x -=y; } else { ans = y + 10; y += x; } A. ans = 60, x = 50, y =100 B. ans = 60, x =0, y =50 C. ans = 45, x = 50, y = 0 D. ans = 45, x = 50, y = 50

Respuesta :

Answer:

B. ans = 60; x = 0; y = 50

Explanation:

(i)First format the code properly as follows:

int ans = 35, x = 50, y =50;

if ( x >= y) {

ans = x + 10;

x -=y;

} else {

ans = y + 10;

y += x;

}

(ii) Taking the if statement of the code;

The if statement block is executed if x is greater than or equal to y (x >= y).

Since x=50 and y=50, then the code continues to execute the statement in the block.

In the if block;

(a) the first line is

ans = x + 10.

Since x = 50, substituting for x gives

ans = 50 + 10 = 60

Therefore ans = 60

(b) the second line is

x -= y

This can be re-written as

x = x - y.

This means that the value of x - y is written back into x. Therefore since x = 50 and y = 50, substituting for x and y gives

x = 50 - 50 = 0

Therefore x = 0

(c) the value of y is not changed at all, therefore y = 50

(iii) Taking the else statement of the code;

Since the if statement of the code has been executed, the else statement is simply skipped.

Therefore the final values of ans, x, y are respectively 60, 0 and 50

Answer:

B. ans = 60, x = 0, y = 50

Step wise Explanation of the code chunk

  • The first statement assigns value 35 to ans variable, value of 50 to x variable and value of 50 to y variable.
  • Next is an if statement which checks if the value of x variable is greater than or equal to y
  • This condition is true as x = 50 and y = 50 So x = y
  • Now since the statement is true it will enter the if block of the code which is the instruction: ans = x + 10; x -=y; and ignores the else block.
  • This line changes the value of ans variable and assigns it the value obtained by adding 10 to the value of variable x.
  • we know that         x = 50

        So

                                      ans = x + 10

                                      ans = 50 + 10

                                          ans = 60

  • After this, comes another line x -=y; which means decrement the value of x by value of y

that means:

                                              x = x - y

                                              x = 50-50

                                                  x = 0

  • So the new value of ans is 60, new value of x is 0 and the value of y remains the same i.e. 50

Hence

                                                ans = 60

                                                    x  =  0

                                                    y  = 50