Question

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 ZZ be an array of 10 elements with Z[i]=1Z[i]=1, for all ii such that 0≤i≤90 \le i \le 9. The value returned by SimpleFunction(Z, 10, 2) is __________

Official answer and solution
Official answer
1023
From
Official GATE 2021 answer key

Solution

Recognize the Horner's rule accumulator pattern and compute the resulting geometric series.

The function SimpleFunction(Y, n, x) initializes total = Y[0] and then iteratively updates:

total=x⋅total+Y[i]for i=1,2,…,n−1\text{total} = x \cdot \text{total} + Y[i] \quad \text{for } i = 1, 2, \dots, n - 1

Expanding this recurrence yields Horner's rule representation for the polynomial:

total=Y[0]xn−1+Y[1]xn−2+⋯+Y[n−2]x+Y[n−1]=∑i=0n−1Y[i]xn−1−i\text{total} = Y[0] x^{n-1} + Y[1] x^{n-2} + \dots + Y[n-2] x + Y[n-1] = \sum_{i=0}^{n-1} Y[i] x^{n-1-i}

For the call SimpleFunction(Z, 10, 2), we have n=10n = 10, x=2x = 2, and Z[i]=1Z[i] = 1 for all 0≤i≤90 \le i \le 9:

total=∑i=091⋅29−i=∑k=092k=210−1=1024−1=1023\text{total} = \sum_{i=0}^{9} 1 \cdot 2^{9-i} = \sum_{k=0}^{9} 2^k = 2^{10} - 1 = 1024 - 1 = 1023
Final answer

1023

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2021 Computer Science and Information Technology (CS, Set-1)
Question
58 of 65, printed as CS Q.48
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.