PLEASE HELP WITH C++!!!! 1. Write a recursive function to check if a given strin
ID: 3939617 • Letter: P
Question
PLEASE HELP WITH C++!!!!
1. Write a recursive function to check if a given string is a palindrome.
First complete given function prototype:
bool isPal(const string &str, int start, int end);
Then use the provided driver program to test your code.
2. Write a recursive function that returns the frequency of occurrence of a particular digit ‘d’ in an integer ‘n’.
First complete given function prototype:
int frequencyCount(int number, int digits);
driver program:
#include <iostream>
#include <string>
using namespace std;
bool isPal (const string &str, int start, int end);
int frequencyCount (int number, int digits);
int main ()
{
string str [5] = {"abcba", "abba", "a", "abc", "abcdabcd"};
for (int i = 0; i < 5; i++)
{
if (isPal(str[i], 0, str[i].length()-1))
cout << "string " << str[i] << "is palindrome!" << endl;
else
cout << "string " << str [i] << "is not palindrome." << endl;
}
cout << endl;
cout << "frequency of 4 in 1342457 is " << frequencyCount(1342457, 4) << endl;
cout << "frequency of 6 in 1342456 is " << frequencyCount (1342457, 6) << endl;
cout << endl;
return 0;
}
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
bool isPal (const string &str, int start, int end)
{
if(start>=end)
return true;
else
{
if(str[start]==str[end])
return true&&isPal(str,start+1,end-1);
else
return false;
}
}
int frequencyCount (int number, int digits)
{
if(number!=0)
{
if(number%10==digits)
return 1+frequencyCount(number/10,digits);
else
return frequencyCount(number/10,digits);
}
else
return 0;
}
int main ()
{
string str [5] = {"abcba", "abba", "a", "abc", "abcdabcd"};
for (int i = 0; i < 5; i++)
{
if (isPal(str[i], 0, str[i].length()-1))
cout << "string " << str[i] << " is palindrome!" << endl;
else
cout << "string " << str [i] << " is not palindrome." << endl;
}
cout << endl;
cout << "frequency of 4 in 1342457 is " << frequencyCount(1342457, 4) << endl;
cout << "frequency of 6 in 1342456 is " << frequencyCount (1342456, 6) << endl;
cout << endl;
return 0;
}
OUTPUT:
string abcba is palindrome!
string abba is palindrome!
string a is palindrome!
string abc is not palindrome.
string abcdabcd is not palindrome.
frequency of 4 in 1342457 is 2
frequency of 6 in 1342456 is 1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.