This is a C Program to copy one string to another using recursion.
This C Program Copies One String to Another using Recursion.
This C Program uses recursive function & copies a string entered by user from one character array to another character array.
Here is the source code of the C program to copy string using recursion. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C Program to Copy One String to Another using Recursion */ #include <stdio.h> void copy(char [], char [], int); int main() { char str1[20], str2[20]; printf("Enter string to copy: "); scanf("%[^\n]s", str1); copy(str1, str2, 0); printf("Copying success.\n"); printf("The first string is: %s\n", str1); printf("The second string is: %s\n", str2); return 0; } void copy(char str1[], char str2[], int index) { str2[index] = str1[index]; // printf ("INDEX IS %d\n", index); if (str1[index] == '\0') return; copy(str1, str2, index + 1); }
1. Define the function prototype by using void copy(char [], char [], int);. The copy() function is used to copy one string to another using recursion.
2. Here, we are reading two string values using the ‘str1’ and ‘str2’ variables. str1 is used to store the input string, str2 is str2 is used to recursively copy the string and calls the function copy(str1, str2, 0);
3. In this C Program, the character from str1 is being copied to str2 until null is encountered in the string. index is incremented by 1 to move the recursion call to next state.
4. While child function returning the control to parent function the character in str1 is copied to str2.
Test case 1 – Here, the entered string is having only plain text.
$ gcc recursive-copy.c -o recursive-copy $ ./recursive-copy Enter string to copy: Welcome to Sanfoundry Copying success. The first string is: Welcome to Sanfoundry The second string is: Welcome to Sanfoundry
Test case 2 – Here, the entered string is having text and numbers.
$ gcc recursive-copy.c -o recursive-copy $ ./recursive-copy Enter string to copy: Taj Mahal 011 Copying success. The first string is: Taj Mahal 011 The second string is: Taj Mahal 011
Test case 3 – Here, the entered string is combination of text, numbers and symbols.
$ gcc recursive-copy.c -o recursive-copy $ ./recursive-copy Enter string to copy: Welcome to Sanfoundry Copying success. The first string is: Welcome to Sanfoundry @ 123! The second string is: Welcome to Sanfoundry @ 123!
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Apply for Computer Science Internship
- Check C Books
- Check Computer Science Books
- Apply for C Internship
- Practice Computer Science MCQs