in c++ Question 1: Implement a recursive function that counts the number of occu
ID: 3733703 • Letter: I
Question
in c++
Question 1: Implement a recursive function that counts the number of occurrences of a character in a string. The function declaration must be: Returns the number of occurrences of n in the string str, starting a position idx of str. int freq(string str, int idx, char n) Use the newly defined function in a new program that prompts the user for a string and a character to kook for in that string Example 1: The output should match the example below Please input a string: ThisIsAString Please input a character to count: i i occurs 2 times in a string of charactersExplanation / Answer
#include <iostream>
using namespace std;
int freq(string str, int idx, char n) {
if(idx == str.length()-1) {
return 0;
} else {
if(str[idx] == n) {
return 1 + freq(str, idx+1, n);
}
else {
return freq(str, idx+1, n);
}
}
}
int main() {
string s;
char ch;
cout<<"Please input a string: "<<endl;
cin >> s;
cout<<"Please input a character to count: "<<endl;
cin >> ch;
cout<<ch<<" occurs "<<freq(s,0,ch)<<" times in a string of chracters"<<endl;
return 0;
}
Output:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.