1

Here's a part of my code, where I am trying to reverse a string recursively:

    char reverse[10];
    gets(reverse);
    reverseString(reverse, (strlen(reverse) - 1));
    void reverseString(char ar[], int n)
    {
        if (n == 0)
        {
            return;
        }
        else
        {
            int temp = ar[n];
            ar[n] = *(ar);
            *(ar) = temp;
            reverseString((ar + 1), (n - 1));
        }
    }

When I enter the string "hello" it changes the string to "ohell". I need it to reverse the string totally to "olleh". Can someone help?

6
  • 5
    The gets() is killing me Commented Mar 2, 2014 at 13:15
  • try to make building blocks. reverse by swapping complete blocks, and once they're swapped recursively swap the internals of the block. Commented Mar 2, 2014 at 13:16
  • 1
    Use a debugger to see what is actually being replaced. You'll be surprised... Commented Mar 2, 2014 at 13:17
  • 1
    You are not stopping the recursion at the correct time. Commented Mar 2, 2014 at 13:18
  • 1
    Never use gets, it's not even in the latest standard anymore. Commented Mar 2, 2014 at 13:29

2 Answers 2

5

Since you swap the first and last element of the array, you should recursively call the function with the remaining n-2 elements (instead of n-1),

void reverseString(char ar[], int n)
{
    if (n <= 0)
    {
        return;
    }
    else
    {
        int temp = ar[n];
        ar[n] = *(ar);
        *(ar) = temp;
        reverseString((ar + 1), (n - 2));
    }
}

(I have assumed that reverseString and reverseAr in your code are actually the same functions, perhaps some copy-paste error.)

Sign up to request clarification or add additional context in comments.

3 Comments

there's also an error for odd length strings that is solved in your answer, with the stop condition n <= 0.
@zmo: Regarding your comment to the now deleted answer: The reverse of "653421" should be "654321" and not "653421".
damn, I'm getting dyslexic on sundays :-s
0
# include <stdio.h>

/* Function to print reverse of the passed string */
void reverse(char *str)
{
   if(*str)
   {
       reverse(str+1);
       printf("%c", *str);
   }
}

/* Driver program to test above function */
int main()
{
   char a[] = "Geeks for Geeks";
   reverse(a);
   getchar();
   return 0;
}

1 Comment

it looks like the OP wants in place reversal of the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.