Copy one string to another using recursion

 Problem statement:- Program to copy one string to another using recursion.

Data requirement:-

   Input Data:-str

  Output Data:-str1

Program in C

Here is the source code of the C Program to copy one string to another using recursion.

Code:

#include<stdio.h>
#include<string.h>
void Copy_String(char str[],char str1[],int i)
{
    str1[i]=str[i];
    if(str[i]=='\0')
        return;
    Copy_String(str,str1,i+1);
}
int main()
{
    char str[30];
    printf("Enter your String:");
    scanf("%[^\n]",str);
    char str1[30]="";
    Copy_String(str,str1,0);
    printf("Copy Done...\n");
    printf("Copy string is: %s",str1);

}

Input/Output:
Enter your String:csinfo360.com
Copy Done...
Copy string is: csinfo360.com

Program in C++

Here is the source code of the C++ Program to copy one string to another using recursion.

Code:

#include<iostream>
#include<cstring>
using namespace std;
void Copy_String(string str,char str1[],int i)
{
    str1[i]=str[i];
    if(str[i]=='\0')
        return;
    Copy_String(str,str1,i+1);
}
int main()
{
    string str;
    cout<<"Enter your String:";
    getline(cin, str);
    char str1[30]="";
    Copy_String(str,str1,0);
    cout<<"Copy Done..."<<endl;
    cout<<"Copy string is: "<<str1;

}

Input/Output:
Enter your String:String recursion
Copy Done...
Copy string is: String recursion

Program in Java

Here is the source code of the Java Program to copy one string to another using recursion.

Code:

import java.util.Scanner;
public class StringCopy {
static void Copy_String(char str[],char str1[],int i)
{
    str1[i]=str[i];
    if(str[i]=='\0')
        return;
    Copy_String(str,str1,i+1);
}
public static void main(String[] args) {
        Scanner cs=new Scanner(System.in);
        String str2;
        System.out.print("Enter your String:");
        str2=cs.nextLine();
        str2+='\0';
        char str[]=str2.toCharArray();
        char str1[]=new char[str.length];
        Copy_String(str,str1,0);
        System.out.print("Copy Done...\n");
        System.out.print("Copy string is: "+String.valueOf(str1));
    cs.close();
}
}

Input/Output:
Enter your String:info360
Copy Done...
Copy string is: info360

Program in Python

Here is the source code of the Python program to copy one string to another using recursion.

Code:

def Copy_String(str, str1,i):
    str1[i]=str[i]
    if (str[i] == '\0'):
        return
    Copy_String(str, str1, i + 1)
str=input("Enter your String:")
str+='\0'
str1=[0]*(len(str))
Copy_String(str, str1,0)
print("Copy Done...")
print("Copy string is:","".join(str1))

Input/Output:

Post a Comment

0 Comments