18.5k views
5 votes
What is the value of result after the following code executes?

int a = 60;
int b = 15;
int result = 10;
if (a = b)
result *= 2;
a. 10
b. 120
c. 20
d. 12
e. code will not execute

User Mobin
by
7.5k points

1 Answer

2 votes

Final answer:

Due to a potential typo in the code where a single equals sign is used instead of a double equals sign for comparison, the value of variable 'result' mistakenly becomes 20 after execution.

Step-by-step explanation:

The question pertains to a segment of code and what the value of the variable result will be after the code executes. There is an error in the code where the if statement uses a single equals sign ('=') instead of a double equals sign ('==') for comparison. Due to this, the statement a = b is an assignment, not a comparison, and it will assign the value of b (which is 15) to a. Consequently, the if condition is always true (since in most programming languages, an assignment within an if statement also returns the value assigned, which is non-zero and thus 'true'). Then the line result *= 2; will execute, doubling the value of result from 10 to 20.

However, the intent of the original question may have been to check for understanding of comparison operations, in which case it could be a typo or misunderstanding. If a double equals sign was used for comparison, the code would not enter the if block because 60 does not equal 15, and the value of result would remain 10. Since we are to ignore typos, and this could potentially be one, the value of result after the code executes is indeed 20, not 10.

User Anton Rodin
by
7.5k points