1,836 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.

1 Answer

Best answer
1 votes
1 votes
  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.

Related questions

0 votes
0 votes
1 answer
1
Rohit Gupta 8 asked Nov 8, 2017
7,129 views
Let A be a square matrix of size n x n. Consider the following program. What is the expected output?C = 100 for(i=0; i<n; i++) for (j=0; j<n; j++) { Temp = A[i][j] + C A[...
0 votes
0 votes
1 answer
2
0 votes
0 votes
1 answer
3
Anirudh Kaushal asked Apr 4, 2022
275 views
#include<stdio.h int main() { char num = '\011'; printf("%d",num); return 0; }
2 votes
2 votes
0 answers
4