This blog is under construction

Sunday 21 July 2013

C program to copy string using recursion

Write a C program to copy one string to another using recursion.


  #include <stdio.h>
  #include <string.h>

  /* copies the source string to destination */
  void strcopy(char *src, char *dest) {
        if (*src != '\0') {
                *dest = *src;
                strcopy(src + 1, dest + 1);
        } else {
                /* terminating with null character */
                *dest = *src;
        }

        return;
  }

  int main() {
        char src[256], dest[256];

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(src, 256, stdin);
        src[strlen(src) - 1] = '\0';

        /* copies input string to given destination */
        strcopy(src, dest);

        /* print the results */
        printf("Source: %s\n", src);
        printf("Destination: %s\n", dest);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:copy me
  Source: copy me
  Destination: copy me


No comments:

Post a Comment