in Programming
1,520 views
2 votes
2 votes
#include <stdio.h>
char str1[100];
char *fun(char str[])  {
    static int i = 0;
    if (*str) 
    {
        fun(str+1);
        str1[i] = *str;
        i++;
    }
    return str1;
}
int main()  {
    char str[] = "GATE CS 2015 Mock Test";
    printf("%s", fun(str));
    return 0;
}

A)GATE CS 2015 Mock Test

B)tseT kcoM 5102 SC ETAG

C)Nothing is printed on screen

D)Segmentation Fault

i think answer should be option C.But the answer given as B.please explation how.

in Programming
by
1.5k views

1 Answer

1 vote
1 vote
Best answer
  if (*str) {
      fun(str+1); // Keeps calling fun with next character as argument
      str1[i] = *str;
      i++;
    }

As long as we have a non-NUL character in *str, code keeps calling fun with (pointer to) next character as argument (and nothing changes due to these callings).

When *str becomes NUL character, function returns str1 and ends, and now control goes to previously called instance of fun(), which assigns character *str to str1[i]. Here *str is last character of string.

So str1 will eventually contain reverse string of str.

Note that, code doesn't insert NUL character explicitly in str1, but since str1 is global variable and so all characters are zero, so str1 is printed correctly.

So option (B) is correct.

1 comment

thanks i was missing the last part smiley

0
0