Write a function strlen_recursive which accepts a pointer to a string and recursively counts the number of characters in the provided string, excluding the null character. This function should return the number of characters in the string.

Respuesta :

Answer:

Following are the function

int strlen_recursive(char *str1)  // recursively counts

{

static int l=0; // static variable  

   if(*str1==NULL)  // string is equal to NULL

   {

     return(l);  // returning length

      }

   else

   {

       l++; // increased the length

       strlen_recursive(++str1);  // recursive function

     }

}

Explanation:

Here we are iterating over the loop and check if string is equal to NULL then it return the length of string otherwise it recursively count the length of string.

Following are the code in C language

#include <stdio.h>//heaader file

int strlen_recursive(char *str1) // recursive function

{

 static int l=0;// static variable  

   if(*str1==NULL)  

   {

   return(l); // return length if string is equal to null

      }

   else

   {

       l++;

       strlen_recursive(++str1); // call recursive function

    }

}

int main() // main function

{

   char str1[100]; // declaring array  

   int l=0;

    printf("Enter the string: ");

   gets(str1);// input string

    l=strlen_recursive(str1); // recursive function

printf("Total number of characters are: %d\n",l);

return 0;

}

Output:

Total number of characters are:sa

2

Q&A Education