Question

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?

Was it helpful?

Solution

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.)

OTHER TIPS

# 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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top