What will be the output of executing the following C code snippet?
Texas Instruments aptitude question, verified with a worked answer. Free to practise - no sign-up.
What will be the output of executing the following C code snippet?
#include <stdio.h>
float WHATISIT(float x, int n) {
if (n >= 1)
return ((n > 0) ? x * WHATISIT(x, n - 1) : 1);
else
return ((n < 0) ? (1.0 / x) * WHATISIT(x, n + 1) : 1);
}
int main(void) {
float t = WHATISIT(2, 3);
float k = WHATISIT(0.5, -3);
printf("%f\n", t);
printf("%f\n", k);
return 0;
}
Show answer & explanation
Answer: C. 8, 8
The function WHATISIT(x, n) implements the mathematical operation x^n. For t = WHATISIT(2, 3), it calculates 2^3 = 8. For k = WHATISIT(0.5, -3), it calculates (0.5)^-3, which is equivalent to (1/0.5)^3 = 2^3 = 8.
Step-by-step Derivation:
Step 1: Analyze the function logic for n >= 1. The ternary operator (n > 0) ? x * WHATISIT(x, n - 1) : 1 will always evaluate to x * WHATISIT(x, n - 1) because n is already >= 1. This is a standard recursive implementation of x^n for positive integers.
Step 2: Trace WHATISIT(2, 3):
- n=3: return 2 * WHATISIT(2, 2)
- n=2: return 2 * WHATISIT(2, 1)
- n=1: return 2 * WHATISIT(2, 0)
- n=0: The condition (n >= 1) is false. It enters the else block. Since (n < 0) is false (0 is not < 0), it returns 1.
- Result: 2 * 2 * 2 * 1 = 8.0.
Step 3: Analyze the function logic for n < 1. The else block handles n <= 0. If n < 0, it returns(1.0 / x) * WHATISIT(x, n + 1). If n = 0, it returns 1.
Step 4: Trace WHATISIT(0.5, -3): - n=-3: return (1.0 / 0.5) * WHATISIT(0.5, -2) = 2 * WHATISIT(0.5, -2)
- n=-2: return (1.0 / 0.5) * WHATISIT(0.5, -1) = 2 * WHATISIT(0.5, -1)
- n=-1: return (1.0 / 0.5) * WHATISIT(0.5, 0) = 2 * WHATISIT(0.5, 0)
- n=0: The condition (n >= 1) is false. In the else block, (n < 0) is false, so it returns 1.
- Result: 2 * 2 * 2 * 1 = 8.0.
Step 5: Final output is 8.000000 and 8.000000 (formatted as %f).