304,685 views
0 votes
0 votes
Consider the following static method, calculate.

public static int calculate(int x)
{
x = x + x;
x = x + x;
x = x + x;

return x;
}
Which of the following can be used to replace the body of calculate so that the modified version of calculate will return the same result as the original version for all values of x?

return 8 * x;
return 3 + x;
return 3 * x;
return 6 * x;
return 4 * x;

User DashRantic
by
2.6k points

1 Answer

14 votes
14 votes

Answer:

return 8 * x

Step-by-step explanation:

Given

The attached code segment

Required

Which single statement can replace the program body

From calculate(), we have:


x = x + x;\\ x = x + x;\\ x = x + x;

The first line (x = x + x) implies that:


x=2x

So, on the next line; 2x will be substituted for x

i.e.


x = x + x becomes


x = 2x + 2x


x = 4x

So, on the third line; 4x will be substituted for x

i.e.


x = x + x becomes


x = 4x+ 4x


x = 8x

In programming: 8x = 8 * x:

This means that: return 8 * x can be used to replace the body

User Mehant Kammakomati
by
3.3k points