Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a string using a recursive function

I am currently studying C and I can't get past this exercise. I must create a recursive function to reverse string1 into string2. Here is my code. I would gladly appreciate your help.

#include <stdio.h>
#define MAX 100

void reverse(char s1[],char s2[],int n,int j);

int main()
{
    char string1[MAX]="How Are You Mate";
    char string2[MAX]="";
    int n=0;
    int i=0;
    int j=0;

    for(i=0;string1[i]!='\0';i++)
        n++;
    reverse(string1,string2,n,j);
    printf("String-a normal:\n%s\n",string1);
    printf("String-a reverse:\n%s\n",string2);
    return 0;
}

void reverse(char s1[],char s2[],int n,int j)
{
     if(n>0)
     {
            s2[j]=s1[n];
            reverse(s1,s2,n-1,j+1);
     }
     else
            s2[j]='\0';
}
like image 380
Lind Avatar asked Jul 29 '26 17:07

Lind


1 Answers

in-place (the caller could make a copy of the string before calling this function) string reverse with tail-recursion

void reverse (char *str, size_t len)
{
  char tmp;
  if (len-- < 2) return;

  tmp = *str;
  *str = str[len];
  str[len] = tmp;

  reverse (str+1, len -1);
}

O, if you don't want pointers:

void reverse (char str[], size_t len)
{
  char tmp;
  if (len-- < 2) return;

  tmp = str[0];
  str[0] = str[len];
  str[len] = tmp;

  reverse (str+1, len -1);
}
like image 145
wildplasser Avatar answered Aug 01 '26 07:08

wildplasser



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!