Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 441
Amol Singh Avatar asked Mar 16 '26 00:03

Amol Singh


2 Answers

Following is one way to reverse string using recursion!

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

void rev_str_recursive(char arr[], size_t iStart, size_t iLast)
{
    if( iStart < iLast )
    {
        //swap
        char temp = arr[iStart];
        arr[iStart] = arr[iLast];
        arr[iLast] = temp;

        rev_str_recursive(arr, ++iStart, --iLast);  
    }
}

void main()
{
    char cArray[] = {"A quick brown fox jumps over a lazy dog"};

    rev_str_recursive(cArray, 0, strlen(cArray)-1);
}
like image 161
AFI Avatar answered Mar 17 '26 12:03

AFI


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.
like image 30
unwind Avatar answered Mar 17 '26 13:03

unwind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!