Open In App

GATE | GATE-CS-2015 (Set 2) | Question 25

Consider the following function written in the C programming language.

The output of the above function on input “ABCD EFGH” is




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

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

Answer: (D)
Explanation: The program prints all characters before ‘ ‘ or ‘\0’ (whichever comes first) in reverse order.



 

Let’s assume that Base address of given Array is 1000. It can be represented as given below in the image



Below is the complete Recursion Stack of the Given Code

After calling foo(1004), recursion will return as character at 1004 is ‘  ’. foo(1004) will return to its caller which is foo(1003) and next line in foo(1003) will be executed which will print character at 1003 (‘D’). foo(1003) will then return to foo(1002) and character at 1002 (‘C’) will get printed and the process will continue till foo(1000).

 

This solution is contributed by Pranjul Ahuja.
Quiz of this Question

Article Tags :