Consider the following function written in the C programming language. void foo(char *a){ if ( *a && *a != ' '){ foo(a+1); putchar(*a); } } The output of the above function on input "ABCD EFGH" is
Topic-wise GATE CS PYQs with verified steps
GATE CSE 2015 Set 2 · Q15
Time
void foo(char *a){
if ( *a && *a != ' '){
foo(a+1);
putchar(*a);
}
}The output of the above function on input "ABCD EFGH" isSelect one answerSingle correct
Solution
Official answer: D) DCBA
RecursionThe function foo(char *a) recursively traverses characters until it reaches either the null terminator \0 or a space character ' ':
foo("ABCD EFGH") sees *a = 'A', calls foo("BCD EFGH").
foo("BCD EFGH") sees *a = 'B', calls foo("CD EFGH").
foo("CD EFGH") sees *a = 'C', calls foo("D EFGH").
foo("D EFGH") sees *a = 'D', calls foo(" EFGH").
foo(" EFGH") sees *a = ' ' (space), so the condition *a != ' ' is false and the function returns without printing.
As the recursion unwinds, putchar(*a) prints each character in reverse order:
putchar('D') prints D
putchar('C') prints C
putchar('B') prints B
putchar('A') prints A
Thus, the printed output is DCBA, which corresponds to Option (D).
Try the question first, then check your work.
Examiner trap
Trace the recursive calls until the space character is encountered. Notice that putchar is called after the recursive call returns, reversing the traversed substring.
This Recursion previous year question is Q15 of the GATE CSE 2015 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. 2 of them are 1-mark MCQs like this one, and GATE CSE 2015 Set 2 has 2.
How GATE tests RecursionIndependent practice explanation verified by the GateAI team. GATE is conducted by the IITs; question text follows the official paper.