GATE / CS ARCHIVE

GATE CSE 2016 SET 1 / QUESTION 34

GATE CSE 2016 Set 1 Q34

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

GATE 2016 Set 1, Q34 2 marks · MCQ
Report issue

Control Flow & Loop Tracing

Question 34, GATE 2016: Fill the loop condition so this C function returns the maximum array element for all n≥1:
int max(int *p,int n){int a=0,b=n−1;while(____){if(p[a]<=p[b])a=a+1;else b=b−1;}return p[a];}
A: a!=n. B: b!=0. C: b>(a+1). D: b!=a.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

At each iteration discard an endpoint no greater than the other: if p[a]≤p[b], advance a; otherwise decrement b. A maximum remains in the surviving interval. Continue until a=b, then return that sole survivor. Condition b!=a is D; stopping with two candidates is premature.

The invariant is that at least one maximum of the original array lies between indices a and b inclusive. Discarding the smaller endpoint preserves this invariant, including ties because the other equal value remains. Each step reduces b−a by 1, so termination occurs after n−1 iterations at a=b. For n=1 the correct loop runs zero times. Option C would stop with two values, potentially returning the smaller left one; A and B tie termination to fixed endpoints rather than convergence.

Original paper, page 14 · Answer key