GATE / CS ARCHIVE

SUBJECT COLLECTION

Programming in C · Recursion

33 questions, newest first

GATE CSE has asked 33 questions on Recursion (Programming in C) from 1994 to 2026, in 23 of the 46 papers; the most recent is in GATE CSE 2026 Set 2. In the last five years it carried 1.6 marks per 100-mark paper on average, against 1.3 since 2003. Since 2014 the questions have been 10 MCQ and 9 NAT. 6 groups of questions here are solved the same way; “One per method” keeps the newest of each.

Browse topics
2 marks · MCQ
Report issue

A terminating recursive list-size function

Recursion

Question 39, GATE 2026: For a nonempty singly linked list, getListSize(head) returns 1 if E1 is true and otherwise returns E2. Choose between base tests head==NULL or head->next==NULL, and recursive expressions 1+getListSize(head) or 1+getListSize(head->next).
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Givens and goal

For a nonempty singly linked list, getListSize(head) returns 1 if E1 is true and otherwise returns E2. Choose between base tests head==NULL or head->next==NULL, and recursive expressions 1+getListSize(head) or 1+getListSize(head->next).

Approach

Match the base return value 1 to a one-node list and ensure recursion moves to a strictly shorter suffix.

Step-by-step solution

1. The input list is nonempty, so the current head points to a node. A one-node list is recognized by a null next pointer, and its length is 1.
2. If a next node exists, the tail beginning there is also nonempty. The total length is one for the current node plus the recursively computed tail length. This supplies the base condition and recursive expression in B.
3. Induction proves correctness: length 1 returns 1; assuming the routine counts a tail of length n−1, the recursive case returns 1+(n−1)=n.
4. Passing the unchanged head recursively never decreases the problem size and does not terminate on longer lists. Using head==NULL as the base test while returning 1 gives an extra count for the empty suffix. These defects eliminate the other choices.

Assumption: As usual for a finite singly linked list, the chain is acyclic. The question's recursion would not terminate on a cyclic structure.

Trace for three nodes A→B→C→NULL: the call at C detects next==NULL and returns 1; the call at B returns 1+1=2; the call at A returns 1+2=3. With a head==NULL base returning 1, even a one-node input would instead return 1+1=2. With an unchanged-head recursive call, any list longer than one node recurses forever rather than reaching the last node.

Original paper, page 28 · Answer key

2 marks · NAT
Report issue

Thresholds of nested integer logarithms

Recursion

Question 61, GATE 2026: The recursive functions are bar(1)=0 and bar(n)=1+bar(n/2) otherwise, using C integer division; foo(1)=1 and foo(n)=1+foo(bar(n)) otherwise. Find the smallest positive integer n for which foo(n)=5.
Tap to enlarge
Answer & solution

Official answer: 65536

Step through it (2 calls)

Givens and goal

The recursive functions are bar(1)=0 and bar(n)=1+bar(n/2) otherwise, using C integer division; foo(1)=1 and foo(n)=1+foo(bar(n)) otherwise. Find the smallest positive integer n for which foo(n)=5.

Approach

First identify bar as a floor logarithm, then work backwards through the thresholds for successive foo return values.

Step-by-step solution

1. For positive n, integer division by 2 repeatedly halves n with truncation. If 2^m≤n<2^(m+1), exactly m divisions are needed to reach 1. Hence bar(n)=floor(log₂n).
2. Therefore foo(n)=1+foo(floor(log₂n)) for n>1, with foo(1)=1. A foo call counts one level and continues with its much smaller floor-logarithm argument.
3. Let a_j be the smallest input with return value j. The base is a₁=1. To obtain one extra level, floor(log₂n) must reach at least the smallest input a_j needed for the previous level. The least n with floor(log₂n)=a_j is n=2^(a_j).
4. Thus the successive thresholds are a₁=1, a₂=2, a₃=4, a₄=16, a₅=2^16=65536. Monotonicity of floor(log₂n) and of these level thresholds shows no smaller input can skip ahead to five levels.
5. Verify directly: bar(65536)=16, bar(16)=4, bar(4)=2, bar(2)=1. The foo chain is 65536→16→4→2→1, giving return values 5→4→3→2→1 when read from the outer call inward.
6. The requested integer is 65536. The division is integer division; treating bar as an unrounded real logarithm would not model the code.

Original paper, page 45 · Answer key

2 marks · NAT
Report issue

Bounding a recursive return value by residues

Recursion

Question 61, GATE 2026: The function computes length=end+1−start. It returns 0 if length<1 or start<0 or end<0. Otherwise if length%3==0 it returns func(start+1,end); if length%3==1 it returns 1+func(start,end−1); else it returns func(start+2,end). Find the maximum possible returned value for defined, non-overflowing C executions.
Tap to enlarge
Answer & solution

Official answer: 1

Givens and goal

The function computes length=end+1−start. It returns 0 if length<1 or start<0 or end<0. Otherwise if length%3==0 it returns func(start+1,end); if length%3==1 it returns 1+func(start,end−1); else it returns func(start+2,end). Find the maximum possible returned value for defined, non-overflowing C executions.

Approach

Follow how the interval length moves between residue classes modulo three.

Step-by-step solution

1. For valid endpoints let L=end+1−start>0. The first branch changes L to L−1, the second to L−1 while adding 1, and the third to L−2. Every valid recursive step strictly decreases L, so it eventually reaches a base case.
2. If L≡0 mod 3, the next length is L−1≡2. The following step subtracts 2, reaching L−3≡0. This 0→2→0 cycle never enters residue 1 and therefore contributes no increment.
3. If L≡2 mod 3, its first step goes directly to L−2≡0, followed by the same zero-contribution cycle. If L≡1 mod 3, it adds 1 once and moves to L−1≡0, after which no further increments occur.
4. Invalid endpoints return zero immediately. The value 1 is attainable with start=end=0: length=1, so the function returns 1+func(0,−1)=1+0.
5. Therefore the maximum is 1. This analysis assumes representable arithmetic; evaluating end+1 or changing endpoints beyond signed-int limits can cause undefined behavior and is not a valid counterexample returning a larger defined integer.

Original paper, page 41 · Answer key

2 marks · NAT
Report issue

Recognizing a recursion that counts runs

Recursion

Question 61, GATE 2025: In C, foo(S,size) returns 0 for size=0, 1 for size=1, otherwise returns 1+foo(S+1,size−1) if S[0]≠S[1], and foo(S+1,size−1) otherwise. main prints foo(A,9) for A={0,1,2,2,2,0,0,1,1}. What is printed?
Tap to enlarge
Answer & solution

Official answer: 5

Step through it (17 steps)

Approach: Interpret each recursive step as testing one adjacent boundary, with the final single element supplying the first run count.
For a nonempty array, every call with size greater than one advances the pointer by one and decreases size by one. It adds 1 exactly when the two currently adjacent values differ. The size-one base case returns 1, so the total is 1 plus the number of adjacent changes.
Here the adjacent-change indicators are 1,1,0,0,1,0,1,0 for the pairs (0,1),(1,2),(2,2),(2,2),(2,0),(0,0),(0,1),(1,1). Their sum is 4; adding the base-case 1 yields 5.
Equivalently, the maximal equal-value runs are [0], [1], [2,2,2], [0,0], [1,1]. There are five runs, so the program prints 5. It does not count distinct numerical values; although only 0,1,2 occur, repeated values separated into different runs contribute separately.

Original paper, page 61 · Answer key

1 mark · MCQ
Report issue

Print on recursive return to reverse input

Recursion

Question 19, GATE 2024: main calls fX once. The function has local char a; it reads a=getchar(), recursively calls fX if a is not newline, then prints a with putchar if a is not newline. Input is 1234 followed by newline. A no termination; B termination with no output; C termination with 4321; D termination with 1234.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Approach: Distinguish the order in which recursive calls read characters from the order in which suspended calls resume printing.
1. The first call stores '1' in its own local a and calls fX again before reaching putchar. The next calls similarly store '2', '3' and '4'. Each call has a separate local variable.
2. A fifth call reads the newline. Both conditions are false, so this call neither recurses nor prints and returns immediately.
3. The suspended call holding '4' now continues at its second condition and prints 4. Returning again prints 3, then 2, then 1.
4. Once the first call returns, main terminates. The newline itself is never printed.
Answer: C, output 4321. Printing before the recursive call would preserve input order; printing after it reverses order. The explicitly supplied newline is the stopping condition, so no assumption about reading past end-of-file is needed.
The printed program uses typographic single quotation marks. Taken literally these are not valid C delimiters, so the program does not compile as printed. The answer above follows the intended textbook interpretation with ASCII quote delimiters.

Original paper, page 13 · Answer key

2 marks · MCQ
Report issue

Recursion

Question 36, GATE 2023: main calls f1(), f2(2), f3() in that order. f1 returns 1; f3 returns 5. f2(X) first calls f3(), then returns f1() if X==1, otherwise returns X*f2(X−1). Describe its activation tree and identify the matching source option.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Main has three ordered children f1, f2(2), f3. The f2(2) activation first calls f3 and then recursively calls f2(1). That activation calls f3 and, because X=1, calls f1. Thus f2(2) has children f3, f2(1), and f2(1) has children f3, f1.

Teaching detail. An activation-tree node represents one invocation, not one distinct function name. The recursive f2 calls at arguments 2 and 1 therefore occupy different nodes. The ordered tree is main[f1, f2(2)[f3, f2(1)[f3,f1]], f3]. Returning a value does not create another activation, so multiplying by X adds no node. Likewise the final f3 called by main is a sibling of f2, not a descendant. This trace verifies both call nesting and left-to-right sibling order.

Original paper, page 35 · Answer key

2 marks · MCQ
Report issue

Recursion

Question 47, GATE 2023: The binary tree has root 10, left child 5 with leaves 3,8, and right child 11 with right leaf 13. C function foo(NULL) returns 0; otherwise it evaluates retval=p->val+foo(p->left)+foo(p->right), prints retval, and returns retval. Find the output under the intended left-before-right evaluation, and explain the C-language caveat. Source options include C: 3 8 16 13 24 50.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Our answer: C under left-before-right recursive evaluation; order not fixed by C

Each call returns its subtree sum and prints that sum after both child calls. The leaf sums are 3, 8, 13; the subtree rooted at 5 sums 16; that at 11 sums 24; the root sums 50. If the left recursive operand is evaluated before the right, the output is 3 8 16 13 24 50, official C. However C does not specify operand evaluation order for +. Evaluating the right subtree first can instead print13 24 3 8 16 50, and the two left leaves may also appear in either order. The printed order is therefore not portable as written; the final return value 50 is stable. Preserve the official answer with this missing evaluation-order assumption disclosed.

Teaching detail. For a node u, the return value obeys sum(u)=value(u)+sum(left)+sum(right), with sum(NULL)=0. The print is after both recursive returns, so children print their subtree totals before their parent prints. The left subtree total is 3+5+8=16; the right is 11+13=24; the root is 10+16+24=50. The parenthesization of additions does not impose an evaluation order on function-call operands in C. The key's ordering is therefore an intended traversal convention, not a portable consequence of the written expression.

Original paper, page 50 · Answer key

1 mark · NAT
Report issue

Recursion

Question 23, GATE 2021: SomeFunction(x,y): if x==1 or y==1 return 1; if x==y return x; if x>y recurse on (x−y,y); if y>x recurse on (x,y−x). Find SomeFunction(15,255).
Tap to enlarge
Answer & solution

Official answer: 15

Step through it (19 steps)

Each recursive step subtracts the smaller positive argument from the larger, preserving their gcd. Starting at(15, 255), repeated subtraction reaches(15, 15), which returns 15. Neither argument reaches 1 on this input.

The invariant gcd(x,y)=gcd(x,y−x) explains correctness, while decreasing x+y proves termination for positive integers. Here y successively becomes 240,225,…,30,15, after sixteen subtractions of 15, and the equality branch returns 15. A modulo-based Euclidean algorithm would skip these repeated subtraction calls.

Original paper, page 65 · Answer key

2 marks · NAT
Report issue

Recursion

Question 49, GATE 2021: foo(x,y,q): if x≤0 and y≤0 return q; if x≤0 return foo(x,y−q,q); if y≤0 return foo(x−q,y,q); otherwise return foo(x,y−q,q)+foo(x−q,y,q). What does printing foo(15,15,10) yield?
Tap to enlarge
Answer & solution

Official answer: 60

Step through it (33 steps)

With q=10, each initial coordinate 15 requires two decrements to become nonpositive. When both remain positive the recursion branches on which coordinate decreases; once one is nonpositive only the other can decrease. Thus leaves correspond to the six interleavings of two x decrements and two y decrements, binomial(4, 2)=6. Each leaf returns 10, so the output is 60. There are no side effects across recursive calls, so unspecified operand evaluation order does not affect this sum.

Let F(i,j) denote the return with i,j remaining decrements needed. Interior recurrence F(i,j)=F(i−1,j)+F(i,j−1), with F(i,0)=F(0,j)=10. Hence F(1,1)=20, F(1,2)=F(2,1)=30, F(2,2)=60. The base is reached at −5, not necessarily exactly zero, because tests are nonpositive.

Original paper, page 85 · Answer key

2 marks · MCQ
Report issue

An unreachable recursive base case

Recursion

Question 26, GATE 2019: For positive integer n, convert(n) executes: if(n<0) printf("%d",n); else { convert(n/2); printf("%d",n%2); }. Decide whether it prints ordinary binary and terminates (A), reversed binary and terminates (B), binary without terminating (C), or nothing without terminating (D).
Tap to enlarge
Your answer
Answer & solution

Official answer: D

1. The stopping branch is n<0, not n==0. Integer division of a positive integer by 2 produces another nonnegative integer, so none of the recursive calls can enter the stopping branch.
2. Repeated halving eventually reaches zero. For example, an input 5 gives calls with arguments 5, 2, 1, 0. At zero the else branch calls convert(0/2), which is convert(0) again.
3. Each printf in the else branch occurs after the recursive call. Since the innermost call never returns normally, no pending printf is reached. The negative-argument printf is also unreachable.
4. Therefore the abstract recursion neither prints nor terminates: D. A real implementation has finite resources and typically exhausts its call stack, rather than literally running forever. The familiar binary-conversion algorithm would need a reachable base case; it cannot be substituted for the code actually supplied.

Original paper, page 9 · Answer key

1 mark · NAT
Report issue

Counting recursive calls

Recursion

Question 21, GATE 2018: Global int counter starts at 0. calc(a,b) increments counter, returns a*a*a if b==3, otherwise sets c=calc(a,b/3) and returns c*c*c. main calls calc(4,81), discards its return, then prints counter. Find the intended output.
Tap to enlarge
Answer & solution

Official answer: 4

Our answer: 4 in intended call-count model; signed-overflow caveat

Method

Count activations on the descent separately from arithmetic on the return path. Calls occur at b=81,27,9,3; the last still increments counter before testing the base case. Unwinding produces mathematical values 4³,4⁹,4²⁷,4⁸¹. Already 4²⁷=2^54 exceeds a signed 32-bit range, and the final 2^162 exceeds signed 64-bit range. Thus counting gives the intended answer, but actual C execution is not guaranteed once signed overflow occurs.

Solution

The b arguments are 81, 27, 9, 3, so counter is incremented four times before the base return. The intended answer is 4. However the return computation then cubes repeatedly to 4^81=2^162, overflowing signed int on ordinary 32-bit or 64-bit implementations. Signed overflow is undefined behavior in C even if main discards the return value, so the printed result is not portable without sufficiently wide integer arithmetic or an explicit abstraction that ignores overflow.

Original paper, page 9 · Answer key

2 marks · NAT
Report issue

Counting prints in recursive cycles

Recursion

Question 45, GATE 2018: Count(x,y) does nothing if y==1. Otherwise, if x!=1 it prints * and calls Count(x/2,y); if x==1 it calls Count(1024,y−1). Integers use truncating division. How many prints result from Count(1024,1024)?
Tap to enlarge
Answer & solution

Official answer: 10230

Method

Separate the fast-changing variable x from the outer progress variable y. For each y>1, x halves ten times, since 1024=210. The x=1 call performs no print and starts the next y cycle with x reset. Values of y that produce prints are 1024 down through 2, a total of 1023, not 1024. The terminal y=1 call returns immediately, regardless of its x value. This counts executed print statements, not recursive invocations.

Solution

For a fixed y>1, x takes 1024, 512,..., 2, yielding 10 prints before reaching 1. Then y decreases by 1 and x resets to 1024. This occurs for y=1024, 1023,..., 2, namely 1023 rounds. At y=1 the function stops without printing. Therefore there are 10*1023=10230 prints in the abstract pseudocode model.

Original paper, page 19 · Answer key

2 marks · MCQ
Report issue

Recursion

Question 35, GATE 2017: Functions: void fun1(int n) { if(n==0)return; printf("%d",n); fun2(n-2); printf("%d",n); }
void fun2(int n) { if(n==0)return; printf("%d",n); fun1(++n); printf("%d",n); }
What does fun1(5) print? A 53423122233445; B 53423120112233; C 53423122132435; D 53423120213243. Assume declarations needed for mutual calls.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Step through it (17 steps)

1. Record entry prints separately from return prints. fun1(5) prints 5 and calls fun2(3); that prints 3, increments its local n to 4, then calls fun1(4).

2. Continuing yields entries fun1(4),fun2(2),fun1(3),fun2(1),fun1(2),fun2(0). The zero call prints nothing. The nonzero entry sequence is 5,3,4,2,3,1,2.

3. Unwind in reverse: fun1(2) prints 2; fun2’s local n is now 2, so it prints 2; subsequent exits print 3,3,4,4,5. Entry string 5342312 plus exit string 2233445 gives 53423122233445, A.

Original paper, page 16 · Answer key

2 marks · MCQ
Report issue

Recursion

Question 36, GATE 2017: int foo(int val) { int x=0; while(val>0) { x=x+foo(val--); } return val; }
int bar(int val) { int x=0; while(val>0) { x=x+bar(val-1); } return val; }
Classify foo(3),bar(3): A return 6,6; B infinite loop,abnormal termination; C abnormal termination,infinite loop; D both terminate abnormally.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Our answer: C under ordinary finite-stack execution

1. Postdecrement in foo(val--) passes the old value, then decrements the caller’s local copy. Therefore foo(3) calls another foo(3), which calls another foo(3), without reaching a base case.

2. On conventional finite-stack execution, this unbounded recursion exhausts the stack and terminates abnormally. The exam uses that resource model; C does not prescribe a universal stack-overflow mechanism.

3. bar(val−1) passes a smaller value without modifying its caller. Calls descend 3,2,1,0, but bar(1) repeatedly calls bar(0) because its own val remains 1. It loops without return. Intended option C.

Original paper, page 16 · Answer key

2 marks · NAT
Report issue

Recursion

Question 37, GATE 2016: Code: int f(int*p,int n){if(n<=1)return 0; else return max(f(p+1,n-1),p[0]-p[1]);} int main(){int a[]={3,5,2,6,4};printf("%d",f(a,5));}. max returns the greater argument. Find the printed value.
Tap to enlarge
Answer & solution

Official answer: 3.0 : 3.0

Our answer: 3

Step through it (13 steps)

The recurrence returns max(0, p[0]−p[1],..., p[n−2]−p[n−1]). For3, 5, 2, 6, 4 the adjacent differences are−2, 3,−4, 2; the maximum with 0 is 3.

Unwind from the end: the one-element suffix returns 0; suffix [6,4] returns max(0,2)=2; [2,6,4] returns max(2,−4)=2; [5,2,6,4] returns max(2,3)=3; the full array returns max(3,−2)=3. The function considers adjacent drops, not arbitrary pairs or absolute differences.

Original paper, page 35 · Answer key

1 mark · MCQ
Report issue

Recursion

Question 21, GATE 2015: C function foo(char*a){if(*a && *a!=' '){foo(a+1); putchar(*a); }}. Output for string “ABCD EFGH”? A ABCD EFGH; B ABCD; C HGFE DCBA; D DCBA.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Recursion stops at the first space without advancing beyond it. Each earlier character is printed only after its recursive call returns, reversing ABCD and producing DCBA, D.

The condition stops recursion when the pointer reaches either the terminator or the first space. Starting at A, the function calls on B, C, D and then the space, where it returns without printing. Printing occurs after each recursive call, so unwinding emits D, C, B, A. No invocation reaches EFGH. Had putchar preceded the recursive call, the first word would print forward instead.

Original paper, page 33 · Answer key

1 mark · NAT
Report issue

Recursion

Question 24, GATE 2015: int fun(int n){int x=1, k; if(n==1)return x; for(k=1; k<n; ++k)x=x+fun(k)*fun(n-k); return x; } Find fun(5).
Tap to enlarge
Answer & solution

Official answer: 51

Step through it (34 steps)

Let F1=1 and Fn=1+sum(Fk F(n−k), k=1..n−1). Then F2=2, F3=5, F4=15, F5=1+15+10+10+15=51. Values fit int in this call.

The function’s accumulator begins at 1 on every call. Its recurrence is F(n)=1+Σ F(k)F(n−k), with F(1)=1. Compute bottom-up: F(2)=1+1=2; F(3)=1+2+2=5; F(4)=1+5+4+5=15. For n=5, the four products are 15, 10, 10, 15, and the initial 1 makes 51. Forgetting the initial 1 would incorrectly substitute a different recurrence.

Original paper, page 34 · Answer key

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

2 marks · MCQ
Report issue

Recursion

Question 42, GATE 2014: For C function int f(int j){static int i=50; int k; if(i==j){printf("something"); k=f(i); return 0;} else return 0;}, which is true? A returns 0 for every j; B prints something for every j; C returns 0 for j=50; D exhausts the runtime stack or loops indefinitely when j=50.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

1. Set up the reasoning. The static variable is initialized once and never modified. Split the trace into j≠50, which returns immediately, and j=50, which repeats exactly the same call state.

2. Derive the result. The static i remains 50 across calls. If j≠50, the function immediately returns 0. If j=50, it prints and calls f(50) again without changing the condition; no call reaches its following return. With ordinary recursive frames the stack is exhausted; an optimization eliminating redundant frames could instead run indefinitely. Thus D, assuming normal successful output operations.

3. Check the interpretation. The return statement after the recursive call is unreachable unless that call returns, and the recursion has no changing measure or base case for 50. Optimizations may affect stack growth but do not create the missing termination condition.

Original paper, page 41 · Answer key

2 marks · MCQ
Report issue

Recursive sum of decimal digits

Recursion

Question 48, GATE 2011: Consider unsigned int foo(unsigned int n, unsigned int r) { if (n>0) return ((n%r)+foo(n/r,r)); else return 0; }. What does foo(345,10) return?

(A) 345
(B) 12
(C) 5
(D) 3
Question 48, GATE 2011: Consider unsigned int foo(unsigned int n, unsigned int r) { if (n>0) return ((n%r)+foo(n/r,r)); else return 0; }. What does foo(345,10) return?

(A) 345
(B) 12
(C) 5
(D) 3
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Step through it (9 steps)

For positive n and base r>1, n%r is the final base-r digit and integer division n/r removes it. The recursive calls therefore sum the digits. With n=345 and r=10, the return is 5+4+3+0=12, option B.

Unroll the calls: foo(345,10)=5+foo(34,10); foo(34,10)=4+foo(3,10); foo(3,10)=3+foo(0,10); the last call returns 0. The call stack then returns 3,7,12 in reverse order. It does not reconstruct the original number because no place-value multiplications are used, and it does not stop after the first remainder. The base case is essential to terminate after all digits have been consumed.

Original paper, page 14 · Answer key

2 marks · MCQ
Report issue

Recursive sum of binary digits

Recursion

Question 49, GATE 2011: Consider unsigned int foo(unsigned int n, unsigned int r) { if (n>0) return ((n%r)+foo(n/r,r)); else return 0; }. What does foo(513,2) return?

(A) 9
(B) 8
(C) 5
(D) 2
Question 49, GATE 2011: Consider unsigned int foo(unsigned int n, unsigned int r) { if (n>0) return ((n%r)+foo(n/r,r)); else return 0; }. What does foo(513,2) return?

(A) 9
(B) 8
(C) 5
(D) 2
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Step through it (23 steps)

The function sums the base-r digits of n. Since 513=512+1=29+1, its binary representation is 1000000001 and has two 1 bits. Consequently foo(513, 2)=2, option D. All intermediate recursive divisions are unsigned integer divisions and terminate at zero.

The successive n values are 513,256,128,64,32,16,8,4,2,1,0. Remainders modulo 2 are 1 at n=513 and n=1 and zero at every other positive step. Summing them produces 2. The exponent 9 tells where the highest bit lies, not how many set bits there are; similarly, the number of recursive positive calls is 10, not the return value. The function counts ones for base 2 because binary digits can only be zero or one.

Original paper, page 14 · Answer key

2 marks · MCQ
Report issue

Recursive alternating arithmetic

Recursion

Question 35, GATE 2010: What value does this C program print?
#include <stdio.h>
int f(int *a,int n) {
 if(n<=0) return 0;
 else if(*a%2==0) return *a+f(a+1,n-1);
 else return *a-f(a+1,n-1);
}
int main(void) { int a[]={12,7,13,4,11,6}; printf("%d",f(a,6)); return 0; }
Options: (A) −9; (B) 5; (C) 15; (D) 19.
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

Step through it (17 steps)

Evaluate from the last array element backward. The empty suffix returns 0; f([6])=6; f([11,6])=11−6=5; f([4,11,6])=4+5=9; f([13,4,11,6])=13−9=4; f([7,13,4,11,6])=7−4=3; finally 12+3=15. The function tests each current element’s parity, not its index. Printed value 15, C.

The recurrence is not a flat alternating sum of the original elements: subtraction applies to the entire recursively computed suffix. Parentheses make the evaluation explicit: 12+(7−(13−(4+(11−6))))=15. Pointer arithmetic a+1 advances to the next integer and n−1 shrinks the remaining array; the parity test examines the value *a at each call.

Original paper, page 8

1 mark · MCQ
Report issue

Recursive paired Fibonacci values

Recursion

Question 18, GATE 2009: C function fun(n, f_p) sets *f_p=1 and returns 1 if n≤1; otherwise t=fun(n−1, f_p), f=t+*f_p, *f_p=t, then returns f. main initializes x=15 and prints fun(5, &x). Choices A 6; B 8; C 14; D 15.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

Step through it (13 steps)

At n=1 the function returns 1 and stores 1 through the pointer, overwriting the initial 15. For n=2, 3, 4, 5 the pairs(returned value, stored value) are(2, 1), (3, 2), (5, 3), (8, 5). The printed return value is 8, B.

The pointer is shared through all recursive calls, so its value must be tracked alongside the returned integer. The deepest call overwrites 15 with 1; thus 15 contributes nothing to the result. Each unwinding step returns the sum of the previous two Fibonacci-like values and stores the former return value for the next step. A trace gives n1:(1, 1), n2:(2, 1), n3:(3, 2), n4:(5, 3), n5:(8, 5). printf uses the returned 8, not the final stored 5.

Original paper, page 4

2 marks · MCQ
Report issue

Recursive string reversal

Recursion

Question 61, GATE 2008: Fill ?1 and ?2 so this historical C program reverses a newline-terminated input string.
void reverse(void) {
 int c;
 if (?1) reverse();
 ?2
}
main() {
 printf("Enter Text"); printf("\n");
 reverse(); printf("\n");
}

(A) ?1: (getchar()!='\n'); ?2: getchar(c);
(B) ?1: ((c=getchar())!='\n'); ?2: getchar(c);
(C) ?1: (c!='\n'); ?2: putchar(c);
(D) ?1: ((c=getchar())!='\n'); ?2: putchar(c);
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. Each invocation must read and retain its own character: ((c=getchar()) != '\n'). Recurse only for a non-newline character, then putchar(c) while unwinding.
2. This prints the input characters in reverse, option D. As written, the base invocation also prints the terminating newline before the reversed characters; main then prints a newline afterward.
3. A and B use getchar instead of output; C tests an uninitialized c. The source uses legacy implicit-int main; interpret the algorithm under its historical C conventions.

Original paper, page 12

2 marks · MCQ
Report issue

Values of matching recurrence implementations

Recursion

Question 75, GATE 2008: Consider these C functions, assuming valid array bounds and the intended unit-cost arithmetic model:
int f1(int n) {
 if(n==0 || n==1) return n;
 else return 2*f1(n-1)+3*f1(n-2);
}
int f2(int n) {
 int i; int X[N],Y[N],Z[N];
 X[0]=Y[0]=Z[0]=0;
 X[1]=1; Y[1]=2; Z[1]=3;
 for(i=2;i<=n;i++) {
  X[i]=Y[i-1]+Z[i-2];
  Y[i]=2*X[i]; Z[i]=3*X[i];
 }
 return X[n];
}
What values do f1(8) and f2(8) return?

(A) 1661 and 1640
(B) 59 and 59
(C) 1640 and 1640
(D) 1640 and 1661
Question 75, GATE 2008: Consider these C functions, assuming valid array bounds and the intended unit-cost arithmetic model:
int f1(int n) {
 if(n==0 || n==1) return n;
 else return 2*f1(n-1)+3*f1(n-2);
}
int f2(int n) {
 int i; int X[N],Y[N],Z[N];
 X[0]=Y[0]=Z[0]=0;
 X[1]=1; Y[1]=2; Z[1]=3;
 for(i=2;i<=n;i++) {
  X[i]=Y[i-1]+Z[i-2];
  Y[i]=2*X[i]; Z[i]=3*X[i];
 }
 return X[n];
}
What values do f1(8) and f2(8) return?

(A) 1661 and 1640
(B) 59 and 59
(C) 1640 and 1640
(D) 1640 and 1661
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. Both functions implement a0=0, a1=1, an=2a(n−1)+3a(n−2). In f2, Y[i]=2X[i] and Z[i]=3X[i], including the initialized indices, so X has exactly that recurrence.
2. Values a2 through a8 are 2,7,20,61,182,547,1640. Thus both return 1640, option C, assuming N≥9.
3. Equivalently an=(3^n−(−1)^n)/4.

Original paper, page 16

2 marks · MCQ
Report issue

Recursive digit printing with value parameters

Recursion

Question 31, GATE 2005: void foo(int n, int sum){int k=0, j=0;if(n==0)return;k=n%10;j=n/10;sum=sum+k;foo(j, sum);printf("%d,", k);} main sets a=2048, sum=0; calls foo(a, sum); prints sum with newline. Output? A8, 4, 0, 2, 14; B8, 4, 0, 2, 0; C2, 0, 4, 8, 14; D2, 0, 4, 8, 0.
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

Step through it (13 steps)

Calls peel off digits 8, 4, 0, 2, but each prints only after its recursive child returns. Thus the visible digits are 2, 0, 4, 8. The sum parameter is passed by value, so main’s sum stays 0. Assuming the usual stdio declaration, the output is 2, 0, 4, 8, 0 followed by a newline, option D; the commas come from the inner printf format.

Each call stores its own last digit k before recursively processing the remaining prefix. Because printing occurs after the child returns, digits appear from most significant to least:2, 0, 4, 8. The sum variable is a by-value local parameter, so changes do not propagate back into main’s sum. Main consequently appends 0, giving D. This question combines recursive output order with parameter passing, not a digit-sum algorithm that returns its result.

Original paper, page 4

Descriptive
Report issue

Complete the recursive Towers of Hanoi function

Recursion

Question 11, GATE 2002: Fill the three blanks in this recursive C template for Towers of Hanoi:
void move(int n, char A, char B, char C) {
    if (____) {
        move(____);
        printf("Move disk %d from pole %c to pole %c\n", n, A, C);
        move(____);
    }
}
The task is to supply the condition and the arguments of both recursive calls.
Tap to enlarge
Shared context

Complete all three blanks of a recursive C function move(n,A,B,C), whose printed central action moves disk n from pole A to pole C. B is the spare pole.

Answer & solution

Answer: Blanks: n > 0; n−1, A, C, B; n−1, B, A, C (no official key was published)

1. Infer the parameter roles from the printed central action. move(n,A,B,C) prints a move of disk n from A to C, so A is the source, C the destination, and B the spare pole. A recursive call must preserve this source/spare/destination order even when the pole names are permuted.

2. Fill the stopping condition. For zero disks there is nothing to move. Therefore execute the body only when n > 0. Using n > 1 would incorrectly skip the required single-disk move.

3. Clear the largest disk. Before disk n can move from A to C, the n−1 disks above it must move from A to B with C available as spare. In the function’s argument order this is move(n−1,A,C,B).

4. Move the largest disk, then restore the smaller tower above it. The printed action moves disk n from A to C. Next transfer the n−1 disks from B to C using A as spare, which is move(n−1,B,A,C).

5. The completed valid C function is:

void move(int n, char A, char B, char C)
{
    if (n > 0) {
        move(n - 1, A, C, B);
        printf("Move disk %d from pole %c to pole %c\n", n, A, C);
        move(n - 1, B, A, C);
    }
}

Use the standard stdio declaration for printf in a complete program. The three blanks, in order, are n > 0; n−1,A,C,B; and n−1,B,A,C.

6. Check n=2 explicitly. The execution moves disk 1 A→B, disk 2 A→C, and disk 1 B→C. Each move is legal and the final tower is on C. For general n, assuming both smaller recursive transfers are legal establishes correctness by induction. The move count satisfies T(0)=0 and T(n)=2T(n−1)+1, hence T(n)=2n−1. Simulation verifies legality and final placement for n=1,…,8.

Original paper, page 8

Descriptive
Report issue

Trace doubled suffix recursion

Recursion

Question 13(a), GATE 2001: abc(s) returns at the null terminator; otherwise it calls abc(s+1) twice and then prints s[0]. main calls abc("123").
Question 13(a), GATE 2001: abc(s) returns at the null terminator; otherwise it calls abc(s+1) twice and then prints s[0]. main calls abc("123").
Tap to enlarge
Answer & solution

Answer: 3323321 (no official key was published)

Step through it (33 steps)

Let F(s) be the string printed by a call. F(empty)=empty and F(cs)=F(s)F(s)c. Therefore F("3")="3", F("23")="3"+"3"+"2"="332", and F("123")="332"+"332"+"1"="3323321". The recursive calls finish before the current character is printed, so the initial character appears last. No spaces or newline are printed.

Original paper, page 9

Descriptive
Report issue

Count recursion output characters

Recursion

Question 13(b), GATE 2001: The preceding abc routine is called on a null-terminated string of n characters, excluding the terminator.
Question 13(b), GATE 2001: The preceding abc routine is called on a null-terminated string of n characters, excluding the terminator.
Tap to enlarge
Answer & solution

Answer: 2^n − 1 characters (no official key was published)

For n=0 the function immediately returns and prints zero characters. For n>0 it makes two calls on length n−1 and prints one character itself. Thus C(0)=0 and C(n)=2C(n−1)+1. Expanding gives C(n)=1+2+4+…+2n−1=2n−1. Equivalently, induction substitutes C(n−1)=2n−1−1 to get 2n−1. The null-terminator calls contribute no output. For n=3 this predicts seven characters, agreeing with 3323321.

Original paper, page 9

2 marks · MSQ
Report issue

Recursive median function and ties

Recursion

Question 2.24, GATE 1999: Trial(a,b,c) returns b if a≥b and c<b; otherwise calls Trial(a,c,b) if a≥b, or Trial(b,a,c). Does it find maximum,minimum,median,or none?
Question 2.24, GATE 1999: Trial(a,b,c) returns b if a≥b and c<b; otherwise calls Trial(a,c,b) if a≥b, or Trial(b,a,c). Does it find maximum,minimum,median,or none?
Tap to enlarge
Select all that apply
Answer & solution

Answer: C on distinct values; not total for arbitrary integers (no official key was published)

For distinct values, a return requires c<b≤a, so b is the median. If a<b, swapping the first two puts the larger first. If a≥b but c≥b, swapping b and c either puts the middle value second or is followed by a first-pair swap; direct enumeration of the six strict orderings confirms termination at the median. Ties expose a defect: Trial(2,1,1) repeatedly calls itself because c<b is false while swapping equal arguments changes nothing. Trial(1,1,1) likewise never returns. Thus C describes the intended distinct-input algorithm, but no unconditional median function is established by the stated unrestricted int signature.

Original paper, page 6

Report issue

Trace value-parameter recursion

Recursion

Question 10(a)(i), GATE 1997: Consider this pseudo-Pascal program, where z is global:
program what;
var z:integer;
procedure recur(x);
begin
  if x<=40 then begin
    x:=x+z;
    recur(x);
    z:=x+10
  end
end;
begin
  z:=10;
  recur(z);
  writeln(z)
end.
If x is passed by value, what is printed?
Question 10(a)(i), GATE 1997: Consider this pseudo-Pascal program, where z is global:
program what;
var z:integer;
procedure recur(x);
begin
  if x<=40 then begin
    x:=x+z;
    recur(x);
    z:=x+10
  end
end;
begin
  z:=10;
  recur(z);
  writeln(z)
end.
If x is passed by value, what is printed?
Question 10(a)(i), GATE 1997: Consider this pseudo-Pascal program, where z is global:
program what;
var z:integer;
procedure recur(x);
begin
  if x<=40 then begin
    x:=x+z;
    recur(x);
    z:=x+10
  end
end;
begin
  z:=10;
  recur(z);
  writeln(z)
end.
If x is passed by value, what is printed?
Tap to enlarge
Answer & solution

Answer: 30. (no official key was published)

Step through it (13 steps)

Pass by value gives every call its own local x, but all calls still share the same global z. It is important not to copy z into each activation or to overwrite a caller's x with its child's final x.

On descent, no assignment z:=x+10 has executed yet: it comes after the recursive call. Therefore z stays 10 while the successive calls enter with x=10,20,30,40,50. The calls entering with 10,20,30,40 first update their local x to 20,30,40,50 respectively. The final call enters with x=50; because 50≤40 is false, it immediately returns.

Now unwind the suspended calls:
Entered x=40, saved updated x=50: assign z=60.
Entered x=30, saved updated x=40: assign z=50.
Entered x=20, saved updated x=30: assign z=40.
Entered x=10, saved updated x=20: assign z=30.

The outer call is last to write the shared global, so writeln(z) prints 30. The temporary value 60 produced by the deepest active body is not the final answer. Also, x=40 does execute its body, because both visual sources show ≤40 rather than <40. The individual marks for this nested leaf are not printed; they are left unknown rather than assigning an invented share of the original group's marks.

Original paper, page 7

Descriptive
Report issue

Recursive exponentiation

Recursion

Question 6, GATE 1994: What function of integer x,n is computed by this program?
function what(x,n):
  value := 1;
  if n > 0 then begin
    if n mod 2 = 1 then value := value*x;
    value := value*what(x*x,n div 2);
  end;
  return value;
Tap to enlarge
Answer & solution

Answer: x^n for n≥0 under exact arithmetic; 1 for n<0. (no official key was published)

1. For n≤0 the conditional is skipped and the return value is one.

2. Write positive n=2k+r, where r∈{0,1}. The function returns xr times what(x²,k).

3. Induct on n. The recursive argument k<n, and the induction hypothesis gives (x²)k. Hence the result is x2k+r=xn.

4. The recursion depth and multiplication count are O(log n). Fixed-width integer overflow can change the numerical result; no word size is specified.

Original paper, page 5

5 marks · Descriptive
Report issue

Maximum recursion depth in Fibonacci

Recursion

Question 21, GATE 1994: fib(n)=1 for n=0 or 1; otherwise fib(n)=fib(n−1)+fib(n−2). The available stack is 64 bytes. Each activation stores only a 2-byte return address and a 2-byte integer parameter. Estimate the largest nonnegative n without overflow. GateForum prints parameter “1” in the header but uses n in the body; GFG uses n.
Tap to enlarge
Answer & solution

Answer: n=16 under the stipulated 4-byte-per-activation model, counting the initial fib call. (no official key was published)

Each active invocation occupies 2+2=4 bytes, so the stack can hold 64/4=16 simultaneously active invocations. The relevant quantity is peak recursion depth, not the exponentially growing total number of calls: completed calls return and free their space before their siblings finish.

Let D(n) be the largest number of simultaneously active fib frames, including the current frame. D(0)=D(1)=1, and for n≥2, D(n)=1+max(D(n−1),D(n−2)). It follows that D(n)=n for n≥1. For example fib(3)→fib(2)→fib(1) contains three active frames; the longest chain from fib(n) descends through n−1,n−2,…,1. The alternative final call at zero has no extra level, because fib(1) is a base case and does not call fib(0).

Therefore n=16 uses exactly 64 bytes, while n=17 needs 68 bytes. Both base cases need just four bytes. This estimate assumes the full 64 bytes are available to fib, its initial activation is stack-resident, and intermediate results, frame links, saved registers and runtime bookkeeping incur no further stack charge, exactly as stipulated. A real implementation may need more storage. Excluding the initial activation would shift the numerical bound to 17, but that is a different accounting convention, not the model used here.

Original paper, page 6