Consider the following C function. void convert(int n){ if(n Which one of the following will happen when the function convert is called with any positive integer n as argument?
Topic-wise GATE CS PYQs with verified steps
GATE CSE 2019 · Q26
Time
void convert(int n){
if(n<0)
printf("%d",n);
else {
convert(n/2);
printf("%d",n%2);
}
}Which one of the following will happen when the function convert is called with any positive integer n as argument?Select one answerSingle correct
Solution
Official answer: D) It will not print anything and will not terminate
RecursionLet us trace the function convert(n) when called with a positive integer :
In the initial call with , the condition n < 0 is false, so it enters the else branch.
In the else branch, it first executes convert(n/2) before printing anything.
Repeated integer division by 2 eventually reduces the argument to 0 (n = 0).
When convert(0) is called:
0 < 0 is false.
The else branch is entered, which immediately calls convert(0/2), i.e., convert(0) again.
This leads to infinite recursive calls of convert(0) because the base case condition is n < 0 instead of n <= 0 or n == 0.
Since the recursive call convert(n/2) appears before printf("%d", n%2), no printf statement is ever reached before the program exhausts its stack space (stack overflow).
Therefore, the function will not print anything and will not terminate, making (D) the correct option.
Try the question first, then check your work.
Examiner trap
Check what happens when the recursive argument reaches . Notice the base condition if (n < 0) and where the printf call is placed relative to the recursive step.
This Recursion previous year question is Q26 of the GATE CSE 2019 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. 10 of them are 2-mark MCQs like this one, and it is the only one in GATE CSE 2019.
How GATE tests RecursionIndependent practice explanation verified by the GateAI team. GATE is conducted by the IITs; question text follows the official paper.