Consider the following ANSI C function: int SimpleFunction(int Y[], int n, int…
2021
Consider the following ANSI C function:
int SimpleFunction(int Y[], int n, int x)
{
int total = Y[0], loopIndex;
for (loopIndex=1; loopIndex<=n-1; loopIndex++)
total=x*total +Y[loopIndex];
return total;
}
Let Z be an array of 10 elements with Z[i]=1, for all i such that 0≤i≤9. The value returned by SimpleFunction(Z,10,2) is __________ .
Attempted by 58 students.
Show answer & explanation
Correct answer: 1023
Answer: 1023
Explanation: The code implements Horner's method. It starts with total = Y[0] and for each subsequent element updates total = x * total + Y[i]. After processing all 10 elements (indices 0 through 9), the final value is
total = Y[0]*2^9 + Y[1]*2^8 + ... + Y[8]*2^1 + Y[9]*2^0
With every Y[i] = 1, this becomes the sum of powers of two from 2^0 to 2^9.
Compute the geometric series: 2^0 + 2^1 + ... + 2^9 = 2^{10} - 1 = 1024 - 1 = 1023.
Therefore SimpleFunction(Z, 10, 2) returns 1023.
A video solution is available for this question — log in and enroll to watch it.