Reverse a given string using recursion

Problem statement:- Program to reverse a given string using recursion.

Data requirement:-

   Input Data:- str_rev

  Output Data:-
Reverse_String(str)

Program in C

Here is the source code of the C Program to reverse a given string using recursion.

Code:

#include<stdio.h>
#include<string.h>
char* Reverse_String(char str[])
{
    static int i=0;
    static char str_rev[30];
    if(*str)
    {
    Reverse_String(str+1);
    str_rev[i++]=*str;
    }
    return str_rev;
}
int main()
{
    char str[30];
    printf("Enter your String:");
    scanf("%[^\n]",str);
    printf("After Reversing String is: %s",Reverse_String(str));
}

Input/Output:
Enter your String:csinfo 360 com
After Reversing String is: moc 063 ofnisc

Program in C++

Here is the source code of the C++ Program to Reverse a given string using recursion.

Code:

#include<iostream>
#include<cstring>
using namespace std;
char* Reverse_String(char str[])
{
    static int i=0;
    static char str_rev[30];
    if(*str)
    {
    Reverse_String(str+1);
    str_rev[i++]=*str;
    }
    return str_rev;
}
int main()
{
    char str[30];
    cout<<"Enter your String:";
    cin.get(str, 30);
    cout<<"After Reversing String is: "<<Reverse_String(str);
}

Input/Output:
Enter your String:reverse string
After Reversing String is: gnirts esrever

Program in Java

Here is the source code of the Java Program to Reverse a given string using recursion.

Code:

import java.util.Scanner;
public class ReverseStringUsingRecursion {
static String Reverse_String(String str)
{
    if(str.isEmpty())
    return str;
    else
    return Reverse_String(str.substring(1))+str.charAt(0);
}
public static void main(String[] args) {
           Scanner cs=new Scanner(System.in);
           String str;
           System.out.print("Enter your String:");
           str=cs.nextLine();
           System.out.print("After Reversing String is: "+Reverse_String(str));
        cs.close();
}
}

Input/Output:
Enter your String:programming practice
After Reversing String is: ecitcarp gnimmargorp

Program in Python

Here is the source code of the Python Program to Reverse a given string using recursion.

Code:

def Reverse_String(str):
    if not str:
        return str
    else:
        return Reverse_String(str[1:]) + str[0]
str=input("Enter your String:")
print("After Reversing String is: ",Reverse_String(str))

Input/Output:

Post a Comment

0 Comments