Write a C program to reverse a string using recursive functions or recursion. In this string example, the stringReverse function accepts the pointer and reverses the character array by calling the function recursively.
#include <stdio.h>
#include <string.h>
void stringReverse(char *Str)
{
if(*Str)
{
stringReverse(Str + 1);
printf("%c", *Str);
}
}
int main()
{
char Str[100];
printf("Please Enter any String to Reverse = ");
fgets(Str, sizeof Str, stdin);
printf("\nString after Reversing = ");
stringReverse(Str);
printf("\n");
}

This program uses the temp variable, recursive functions (recursion), and pointers to reverse a given string. I suggest you refer to the C program to reverse a string article and the C string article.
#include <stdio.h>
#include <string.h>
void stringReverse(char *Str, int i, int len)
{
char temp;
if (i >= len)
{
return;
}
temp = *(Str + i);
*(Str + i) = *(Str + len);
*(Str + len) = temp;
stringReverse(Str, ++i, --len);
}
int main()
{
char Str[100];
printf("\nPlease Enter any Text = ");
fgets(Str, sizeof Str, stdin);
stringReverse(Str, 0, strlen(Str) -1);
printf("\nResult = %s\n", Str);
return 0;
}
Please Enter any Text = hello c programmers
Result =
sremmargorp c olleh
It is another example to reverse a string using recursion. For more, refer to the C examples page.
#include <stdio.h>
void stringReverse()
{
char ch;
scanf("%c", &ch);
if(ch != '\n')
{
stringReverse();
printf("%c", ch);
}
}
int main()
{
printf("Please Enter any Text = ");
stringReverse();
printf("\n");
}
Please Enter any Text = c examples
selpmaxe c
Using pointer
#include <stdio.h>
#include <string.h>
void recStr(char *left, char *right)
{
if (left < right)
{
char temp = *left;
*left = *right;
*right = temp;
recStr(left + 1, right - 1);
}
}
void recRev(char *str)
{
recStr(str, str + strlen(str) - 1);
}
int main()
{
char s[100] = "New Delhi";
recRev(s);
printf("%s", s);
}
ihleD weN
Also Read