171k views
4 votes
Write a recursive, int-valued function, 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.

User Ken Colton
by
7.9k points

1 Answer

1 vote

Answer:

The program to this question can be given as:

Program:

#include<iostream> //include header file.

using namespace std; //using namespace

int len(string s) //define method.

{

if(s=="") //if block

{

return 0; //return value.

}

else //else block

{

return 1+len(s.erase(0,1)) ; //return value.

}

}

int main() //main method.

{

string s; //define variable.

int X1; //define variable.

cout<<"Enter string value: "; //message.

cin>>s; //input string value.

X1=len(s); //calling function that holds value in x1 variable

cout<<X1; //print variable x value.

return 0;

}

Output:

Enter string value: xxth

4

Explanation:

The description of the above C++ language program can be given as:

  • In the program first, we include the header file then we define the method that is "len" in this method we pass the string variable that is "s".
  • Inside the len() method, we define a conditional statement in the if block we check if the value of s variable is equal to ("") empty. It will return 0 else it will return the count value of s variable.
  • Then we define a main method inside the main method we define two variable that is "s and X1".
  • s is a string variable that is used to take user input from the user and pass this variable into function.
  • X1 is an integer variable that is used for hold function return value and print its value.
User Tomper
by
7.4k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.