The GATE Grind

GATE 2021 CS (CS1) – Question 58

Programming and Data Structures · Programming in C · 2 marks · Numerical answer

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 \le i \le 9$. The value returned by SimpleFunction(Z, 10, 2) is ______.

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 1023

Explanation

`SimpleFunction` computes
`total = Y[0]; for each next element: total = x*total + Y[k]`.

This is **Horner's rule** for the polynomial $Y_0x^{n-1}+Y_1x^{n-2}+\dots+Y_{n-1}$. With all $Y_i=1$, $n=10$ and $x=2$:
$$2^9+2^8+\dots+2^0=2^{10}-1=\mathbf{1023}.$$

More Programming in C questions

All Programming in C questions →