Given a string, Reverse the string using Recursion. [using single string]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Swap function to swap the characters */
void swap(char *x,char *y)
{
char temp;
temp=*x;
*x=*y;
*y=temp;
}
/* Reverse recursive function to reverse the received string */
void reverse(char *s,int i,int n)
{
/* Swap the first character and the last character of the string */
swap((s+i),(s+n));
/* If the starting index and ending index meet or if their difference is 1, stop swapping and print the string */
if(i==n || n-i==1)
{
printf("%s",s);
return;
}
/* Recursively call the reverse the function & increment the starting index, decrement the ending index */
reverse(s,i+1,n-1);
}
int main(void) {
char *s;
int len;
/* Dynamically allocate memory to store the input string */
s=(char*)malloc(sizeof(char));
/* Get the input string from the user */
scanf("%s",s);
/* Calculate the length of the received string */
len=strlen(s)-1;
/* Call the function to reverse the string */
reverse(s,0,len);
return 0;
}