This blog is under construction

Sunday 21 July 2013

C program to find the length of a string using recursion

Write a C program to find the length of a string using recursion.


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

  /* finds length of the given string using recursion */
  int stringLength(char *str, int len) {

        if (*str != '\n') {
                len++;
                len = stringLength(str + 1, len);
        }
        return len;
  }

  int main() {
        char str[256], len = 0;

        /* get the input string from the user */
        printf("Enter your input string:");
        /* fgets appends \n with user input */
        fgets(str, 256, stdin);

        /* finds the length of the given input string */
        len = stringLength(str, len);

        /* print the result */
        printf("Length of the given input string is %d\n", len);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:Calculate my length
  Length of the given input string is 19


No comments:

Post a Comment