Write a recursive int valued method len that accepts a stri
Write a recursive, int -valued method , len, that accepts a string and returns the number of characters in the string .
The length of a string is:
0 if the string is the empty string (\"\").
1 more than the length of the rest of the string beyond the first character .
Solution
/*calculate length of string using recursion.*/
#include <stdio.h>
int str(char *string)
{
static int length=0;
if(*string!=NULL)
{
length++;
str(++string);
}
else
{
return length;
}
}
int main()
{
char string[100];
int length=0;
printf(\"Enter a string: \");
gets(string);
length=str(string);
printf(\"String length: %d\ \",length);
return 0;
}
/* sample output
Enter a string: hello
String length: 5
*/
