Here is another approach.  Remove the first character.  Reverse the
rest of the string recursively.  Append the character at the end.
Others have given solutions along these lines, but they have various
mistakes.  Here's one that I believe is correct.  As pointed out
already, this is not a good place to apply recursion, but it's an
interesting puzzle.

#include <stdio.h>
#include <string.h>

// Reverse src having length len to dst.
char *reverse(char *dst, char *src, int len)
{
  if (len > 0) {
    char ch = src[0];   // get 1st char
    reverse(dst, &src[1], len - 1); // reverse rest
    dst[len - 1] = ch;  // append 1st at end
  }
  return dst;
}

char *strrev(char *s) { return reverse(s, s, strlen(s)); }

int main(void) {
  char s[] = "The quick brown fox jumped...";
  printf("%s\n", strrev(s));
  return 0;
}

On Sep 23, 1:59 pm, Albert <alberttheb...@gmail.com> wrote:
> How to reverse a String using recursion in C without using any extra
> memory?
>
> the question seems to be simple.....
>
> char* strrev(char *)
> {
>     ...
>     ...
>     ...
>
> }
>
> Try to give all the answers for this prototype.....

-- 
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to algoge...@googlegroups.com.
To unsubscribe from this group, send email to 
algogeeks+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/algogeeks?hl=en.

Reply via email to