GATE 2015 COMPUTER SCIENCE & INFORMATION TECH. – CS – C Programming | Q. 21 (Session – 2)

💻 GATE 2015 – C Programming | Question 21

Question Type: MCQ   |   Topic: Recursion and Character Pointers

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 the input “ABCD EFGH” is:

(A) ABCD   EFGH      (B) ABCD
(C) HGFE   DCBA      (D) DCBA

💡 If you are new to recursion, first read our basic 1 + 2 + 3 + 4 + 5 recursion example . Then continue with this post to practice and solve more C recursion problems. This will help you understand recursion step by step and build a strong foundation in C programming.

🔄 What is Recursion?

The given question involves recursion technique. Recursion is a technique in which a function calls itself to solve a problem step by step. Think of a computer searching through a folder and its sub-folders: one folder may contain another folder, which may contain more folders, so the same searching task is repeated for each folder until there are no more folders to explore. Similarly, a family tree contains parents, grandparents, great-grandparents, and so on, where the same idea can be repeated for each generation. In programming, recursion continues solving smaller versions of the same problem until a stopping condition is reached.

💡 Simple idea: A problem is suitable for recursion when it can be broken into smaller problems of the same type, with a clear condition that tells the function when to stop.

💻 Complete C Program – Try It Yourself

The GATE question gives only the recursive function. To test the program in an online or offline C compiler, we need to add the required header file, main() function, and input statement. Copy the complete program below and run it with the input ABCD EFGH.

#include <stdio.h>

void foo(char *a)
{
    if (*a && *a != ' ')
    {
        foo(a + 1);
        putchar(*a);
    }
}

int main()
{
    char str[100];

    printf("Enter a string: ");
    scanf("%[^\n]", str);

    printf("Output: ");
    foo(str);

    return 0;
}
⌨️ Sample Input: ABCD EFGH
▶️ Output: DCBA

⚠️ Important: Notice that the function stops when it encounters a space character. Therefore, the characters EFGH are never processed. The interesting part is that putchar(*a) comes after the recursive call, so the characters are printed while the recursive calls are returning.

🧩 Step 1: Understand the Function and Input

Before tracing the recursion, let us first understand what the function receives and where the pointer a is pointing.

1️⃣ Function
void foo(char *a)
{
    if (*a && *a != ' ')
    {
        foo(a + 1);
        putchar(*a);
    }
}
2️⃣ Input String
"ABCD EFGH"
3️⃣ Memory Representation
A  B  C  D  _  E  F  G  H  \0
^
a

_ represents a space character.

💡 What happens initially?
The pointer a initially points to the first character A. Therefore, *a is A. Since A is neither '\0' nor a space, the condition *a && *a != ' ' is true.

The function then executes foo(a + 1). This moves the pointer to the next character. The same process continues for A → B → C → D. When the pointer reaches the space after D, the condition becomes false and the recursion stops.

🔁 Step 2: Follow the Recursive Calls

The function keeps calling foo(a + 1) as long as *a is not '\0' and is not a space. Therefore, the pointer moves through the characters A → B → C → D.

🔎 The condition is:

*a && *a != ' '

For A, B, C and D, the condition is true, so another recursive call is made.

➡️ So the recursive calls occur in this order:

A → B → C → D
⛔ When a reaches the space:
*a == ' '

Therefore, *a != ' ' becomes false. The if block is not executed, and the recursion stops here.

📚 What has happened to the call stack?

Each recursive call is placed on the call stack. At the space, no new recursive call is made. The stack has therefore grown up to the call for D.

foo("ABCD EFGH")
    └── foo("BCD EFGH")
         └── foo("CD EFGH")
              └── foo("D EFGH")
                   └── foo(" EFGH")   ← stops here
💡 Important: Notice that putchar(*a) has not printed anything yet. The recursive calls are made first because foo(a + 1) appears before putchar(*a) in the function.

🔙 Step 3: Returning from the Recursive Calls

When the pointer reaches the space, the condition becomes false and that recursive call finishes. The function then starts returning one call at a time. Remember that putchar(*a) appears after the recursive call, so the character is printed only when that particular recursive call returns.

1️⃣ Return to foo("D EFGH")
putchar(*a);
Here *a is D, so D is printed.
2️⃣ Return to foo("CD EFGH")
putchar(*a);
Here *a is C, so C is printed.
3️⃣ Return to foo("BCD EFGH")
putchar(*a);
Here *a is B, so B is printed.
4️⃣ Return to foo("ABCD EFGH")
putchar(*a);
Here *a is A, so A is printed.
🖨️ Characters are printed in this order:
D → C → B → A
Therefore, the final output is DCBA
🧠 Why does this happen?

The reason is the order of the two statements:

foo(a + 1);       /* recursive call */
putchar(*a);      /* executed after recursion returns */

Think about a computer folder containing another folder, which contains another folder, and so on:

📁 Folder A
  ↳ 📁 Folder B
    ↳ 📁 Folder C
      ↳ 📁 Folder D

You enter A, then go inside B, then C, and finally D. You cannot exit Folder A first because you are still inside Folder B, C, and D. When you start coming back, you must exit Folder D first, then C, then B, and finally A.

📁 Folder analogy: Go inside → A → B → C → D  |  Come back → D → C → B → A

Recursion works in a similar way. The last recursive call made is the first one to return. This is called Last In, First Out (LIFO), which is the basic behavior of the function call stack.

🔎 Important Observation

The function never processes the characters after the first space. In this input, the space occurs immediately after ABCD.

A  B  C  D  _  E  F  G  H  \0
_ represents a space.

When a reaches this space, *a != ' ' becomes false. Therefore, the if block is not executed and the recursion stops completely. It does not restart after the space.

🎯 Final Output

Characters printed while returning:
D → C → B → A
Output: DCBA
✅ Correct Answer: (D) DCBA
💡 A Simple Way to Remember
  • foo(a + 1) moves forward through the string.
  • putchar(*a) executes while coming back from recursion.
  • Therefore, the characters before the first space are printed in reverse order.
➡️ Go forward: A → B → C → D   |   🔙 Come back: D → C → B → A

🖨️ What is putchar()?

putchar() is a C library function used to print one character on the screen. In our program, putchar(*a) prints the character currently pointed to by the pointer a.

📌 Syntax
putchar(character);
🔹 Simple Example
putchar('A');

Output: A

🔍 In our GATE question
putchar(*a);

Here, *a means the character stored at the location pointed to by a. Therefore, if a points to A, putchar(*a) prints A. If it points to D, it prints D.

💡 Important for this question: putchar(*a) does not execute immediately. It comes after the recursive call foo(a + 1). Therefore, the program first moves forward through the string and only then prints the characters while returning from recursion.
➡️ Go forward: A → B → C → D   |   🔙 Print while returning: D → C → B → A
⚠️ An Important Rule of Recursion

🔴 Every recursive solution must have a
BASE CONDITION
to stop the recursion.

💡 In C, an if statement is commonly used to check the base condition.
🧠 Remember: A recursive function needs two essential ideas: (1) a recursive call that works on a smaller version of the problem, and (2) a base condition that tells the function when to stop.
📌 Note: The base condition does not have to be written specifically with an if statement. Other control mechanisms can also be used. However, for beginners, if is the most common and easiest way to express the stopping condition in a recursive function.

🧠 Understanding Recursion Using a Stack

When a function calls itself, the computer creates a new stack frame for that function call. In our foo() function, each recursive call moves the pointer one character forward. The calls continue until the pointer reaches the first space character.

📚 Think of a Stack

Think of a stack of books or plates. A new item is placed on the top. When removing items, the item placed last must be removed first. The same idea is used by the function call stack.

💻 Our Recursive Function

void foo(char *a)
{
    if (*a && *a != ' ')
    {
        foo(a + 1);
        putchar(*a);
    }
}

🔽 Step 1: Going Deeper

The input is: ABCD EFGH. The pointer starts at A. Since A is not a space and is not '\0', the function calls foo(a + 1).

A → B → C → D → SPACE

Thus, the function keeps going deeper through A, B, C and D.

📦 Step 2: Stack Frames Are Created

Each recursive call creates a new stack frame:

foo("ABCD EFGH")      ← A
    foo("BCD EFGH")   ← B
        foo("CD EFGH") ← C
            foo("D EFGH") ← D
                foo(" EFGH") ← SPACE

At the space, the condition becomes false. Therefore, no further recursive call is made.

🛑 Important Point: Recursion Stops at the Space

When a points to the space, *a != ' ' becomes false. The if block is skipped and the recursion stops. The function does not continue to EFGH.

A → B → C → D → SPACE ✋ STOP

🔄 LIFO — Last In, First Out

The last recursive call made is the first call to return. This is the Last In, First Out (LIFO) behavior of the function call stack.

Last call: D → returns first
C → returns next
B → returns next
A → returns last

🔙 Step 3: Returning Back

Now the recursive calls start returning. Only now does putchar(*a) execute.

Return from D → putchar('D') → D printed
Return from C → putchar('C') → C printed
Return from B → putchar('B') → B printed
Return from A → putchar('A') → A printed

🎯 Final Output

D → C → B → A
Therefore, the output is DCBA

💡 A Simple Way to Remember

  • foo(a + 1) → goes forward through the string.
  • The first space → stops the recursion.
  • putchar(*a) → executes while coming back.
  • Therefore: Go forward A → B → C → D and come back D → C → B → A .
✅ GATE 2015 Question 21 — Correct Answer: (D) DCBA

🔄 Returning Back: Unwinding the Recursive Calls

The recursive function has reached the space character, so it cannot make another recursive call. Now the function calls begin to return one by one. During each return, putchar(*a) is executed.

📚 Think about our stack of plates

Each recursive call added a new frame to the top of the call stack. Now we start removing those frames from the top. The last call added is the first call to return. This is the LIFO (Last In, First Out) rule.

🛑 First, the space is reached

foo(" EFGH")

Here *a is a space, so *a != ' ' is false. The if block is skipped and this function call returns immediately.

🔙 The calls now return in reverse order

foo(" EFGH")  → returns
foo("D EFGH") → putchar('D') → prints D
foo("CD EFGH") → putchar('C') → prints C
foo("BCD EFGH") → putchar('B') → prints B
foo("ABCD EFGH") → putchar('A') → prints A

📚 What happens to the stack?

The top stack frame returns first. Then the next frame returns, followed by the next one, until the original call finally returns.

Space → D → C → B → A

Notice that the space does not get printed. Its function call simply returns because the condition is false.

🔁 Going Deeper → Reaching the Space → Returning Back

Going deeper: A → B → C → D → SPACE
Unwinding: SPACE → D → C → B → A
🎯 Finally, putchar(*a) prints the characters in reverse order:
D → C → B → A
Therefore, the output is DCBA
0

Gopal Krishna

Hey Engineers, welcome to the award-winning blog,Engineers Tutor. I'm Gopal Krishna. a professional engineer & blogger from Andhra Pradesh, India. Notes and Video Materials for Engineering in Electronics, Communications and Computer Science subjects are added. "A blog to support Electronics, Electrical communication and computer students".

Leave a Reply

Your email address will not be published. Required fields are marked *

Translate »