GateAI
Recursion

GATE CSE 2015 Set 2 · Q15

MCQ1 markEasy

Time

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

Select one answerSingle correct

Pick an option to check

Solution

Step-by-step verified solution

Official answer: D) DCBA

Recursion

The function foo(char *a) recursively traverses characters until it reaches either the null terminator \0 or a space character ' ':

  1. foo("ABCD EFGH") sees *a = 'A', calls foo("BCD EFGH").

  2. foo("BCD EFGH") sees *a = 'B', calls foo("CD EFGH").

  3. foo("CD EFGH") sees *a = 'C', calls foo("D EFGH").

  4. foo("D EFGH") sees *a = 'D', calls foo(" EFGH").

  5. 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') →\to prints D

  • putchar('C') →\to prints C

  • putchar('B') →\to prints B

  • putchar('A') →\to prints A

Thus, the printed output is DCBA, which corresponds to Option (D).

Try the question first, then check your work.

Think the official key or this write-up is wrong?

Report error or challenge

Examiner trap

The misconception this question tests

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

Where do you stand for GATE?

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.

One GATE CSE PYQ every morning

An official question by email at 7 AM IST, with a link to its verified solution. Unsubscribe in one click.

Recursion in GATE CSE

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 Recursion

More from GATE CSE 2015 Set 2

Share this solution

A plain-text card for WhatsApp or Telegram study groups.

GateAI solution cardGATE CSE 2015 Set 2 · Q15 · MCQ

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

Independent practice explanation verified by the GateAI team. GATE is conducted by the IITs; question text follows the official paper.