GATE / CS ARCHIVE

GATE CSE 2021 SET 1 / QUESTION 48

GATE CSE 2021 Set 1 Q48

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2021 Set 1 paper

GATE 2021 Set 1, Q48 2 marks · NAT
Report issue

Control Flow & Loop Tracing

Question 48, GATE 2021: 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;} Array Z has ten elements, all equal to 1. Find SimpleFunction(Z,10,2).
Tap to enlarge
Answer & solution

Official answer: 1023

The loop performs Horner evaluation. Starting at total=1, each of the nine iterations replaces total by 2*total+1. After k iterations total=2^(k+1)-1, so after nine iterations the result is 2^10-1=1023. All intermediate results are within even the minimum standard signed-int range.

The values after initialization and each iteration are 1,3,7,15,31,63,127,255,511,1023. An induction proves total after k loop iterations is 2k+1−1: base k=0 is 1, and 2(2k+1−1)+1=2k+2−1. More generally the function evaluates Y[0]xn−1+Y[1]xn−2+...+Y[n−1] in n−1 multiplications, which is Horner's method.

Original paper, page 39 · Answer key