Write a program called “recursive_algos.cpp” that contains two recursive and one
ID: 3688787 • Letter: W
Question
Write a program called “recursive_algos.cpp” that contains two recursive and one nonrecursive functions
PROGRAM MUST BE WRITTEN IN C++
1. A recursive boolean function called palindrome that accepts one string argument and returns true if the string reads the same forward as it does backwards. For example madam, 463364, and “ABLE WAS I ERE I SAW ELBA” are all palindromes
2. A recursive function called printReverse that accepts one string argument and returns the reverse of that string.
3. A nonrecursive function called printIterReverse that accepts one string argument and returns the reverse of that string
Consider the following prototypes for the functions:
bool palindrome(string & s);
string printReversel(string & s);
string printIterReverse(string & s);
PROGRAM MUST BE WRITTEN IN C++
Explanation / Answer
hey heres the code:
#include<iostream>
#include<string.h>
using namespace std;
bool palindrome(string & s);
string printReversel(string & s);
string printIterReverse(string & s);
int main()
{
string str;
cout<<"enter string : ";
cin>>str;
if(palindrome(str))
cout<<" given string is palindrome.";
else
cout<<" given string is not palindrome.";
cout<<" reverse of the given string is: "<<printReversel(str);
cout<<" Reverse of string (using iteration): "<<printIterReverse(str);
}
bool palindrome(string & s)
{
int n=s.length()-1;
if(s.length()>2)
{
if(s[0]==s[n])
{
if(s.length()!=3||s.length()!=2)
{
std::string str2 = s.substr (1,n-1);
return palindrome(str2);
}
}
else
return false;
}
return true;
}
string printReversel(string & s)
{
std::string str=s.substr(0,s.length()-1);
if(s.length()==1)
return s.substr(0,10);
return s[s.length()-1]+printReversel(str);
}
string printIterReverse(string & s){
string str;
int i,l=0;
for(i=s.length()-1;i>=0;i--)
{
if(l==0)
str=s[i];
else
str=str+s[i];
l++;
}
return str;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.