Consider the following ANSI C program. #include int foo(int x, int y, int q) { if ((x The output of the program upon execution is …
Topic-wise GATE CS PYQs with verified steps
GATE CSE 2021 Set 2 · Q49
Time
#include <stdio.h>
int foo(int x, int y, int q)
{
if ((x <= 0) && (y <= 0))
return q;
if (x <= 0)
return foo(x, y-q, q);
if (y <= 0)
return foo(x-q, y, q);
return foo(x, y-q, q) + foo(x-q, y, q);
}
int main()
{
int r = foo(15,15,10);
printf("%d", r);
return 0;
}The output of the program upon execution is ________.Your answerNumerical answer
Solution
Official answer: 60
RecursionWe need to trace the execution of foo(15, 15, 10):
Call foo(15, 15, 10):
Since and , it executes:
Evaluate foo(15, 5, 10):
For foo(15, -5, 10): since , it calls foo(15 - 10, -5, 10) = foo(5, -5, 10).
For foo(5, -5, 10): since , it calls foo(-5, -5, 10).
For foo(-5, -5, 10): since and , it returns .
Thus, foo(15, -5, 10) = 10.
For foo(5, 5, 10):
foo(5, -5, 10) returns .
foo(-5, 5, 10): since , it calls foo(-5, -5, 10) which returns .
Thus, foo(5, 5, 10) = 10 + 10 = 20.
Therefore:
Evaluate foo(5, 15, 10):
Due to symmetry with respect to and :
Final Value:
Hence, the output printed is 60.
Try the question first, then check your work.
Examiner trap
Trace the recursive call tree for foo(15, 15, 10). Notice that each branch terminates and returns whenever both and .
This Recursion previous year question is Q49 of the GATE CSE 2021 Set 2 paper. Find more GATE CSE PYQs on Recursion in Programming and Data Structures, or browse all GATE CSE PYQs.
Free diagnostic
Take the 20-minute diagnostic: the 3 topics that cost you the most marks, and a rank range. Or sit 5 related Recursion PYQs now with no account.
An official question by email at 7 AM IST, with a link to its verified solution. Unsubscribe in one click.
Recursion has 19 GATE CSE PYQs across 15 papers from 2011 to 2026. 5 of them are 2-mark NAT questions like this one, and it is the only one in GATE CSE 2021 Set 2.
How GATE tests RecursionIndependent practice explanation verified by the GateAI team. GATE is conducted by the IITs; question text follows the official paper.