GATE / CS ARCHIVE

GATE CSE 2015 SET 3 / QUESTION 38

GATE CSE 2015 Set 3 Q38

Programming in C · Recursion · Full GATE CSE 2015 Set 3 paper

GATE 2015 Set 3, Q38 2 marks · MCQ
Report issue

Recursion

Question 38, GATE 2015: Consider this recursive C function:
void get(int n) { if(n<1) return; get(n-1); get(n-3); printf("%d",n); }
If main invokes get(6), how many total invocations of get occur before control returns to main, including the initial invocation and calls that immediately return? Options: (A) 15; (B) 25; (C) 35; (D) 45.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Step through it (24 steps)

1. For n≤0 the invocation still counts once even though it immediately returns. Starting with C(−2)=C(−1)=C(0)=1, repeatedly apply the recurrence upward; omitting the base-case calls would count printed values rather than invocations.

2. Count every invocation including base cases and the initial call. C(n)=1 for n<1 and C(n)=1+C(n−1)+C(n−3) otherwise. Thus C1=3, C2=5, C3=7, C4=11, C5=17, C6=25. Answer B.

Original paper, page 66 · Answer key