Amol Singh Amol Singh - 1 month ago 18
C Question

Reversing a string in c with recursion

I have written code to reverse a string in c... it works fine but I can't return the reversed string in the

main()
function.

#include<stdio.h>

main()
{
char a[17]="abcdefg";
reverse(a);
printf("\n");
system("PAUSE");
}
int reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
}
printf("%c",*a);
}


it prints the reversed string but I want the reversed string in
main()
. How can I do this?

Answer

You need to modify the string, i.e. the input buffer to reverse(), instead of just printing it.

Doing this recursively seems a bit obnoxious, but should of course be possible.

Basically, I guess the printing becomes an assignment, something like this:

  1. Base: The reversal of an empty string is the empty string.
  2. Step: The reversal of a string begins by swapping the first and last characters, then recursing over the remainder of the string.
Comments