//Write a recursive function, vowels, that returns the number of vowels in a str
ID: 3627726 • Letter: #
Question
//Write a recursive function, vowels, that returns the number of vowels in a string. Also write a program to test your function.#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int vowelA (string word)
{
string str (word);
size_t found = str.find_first_of("a");
if (found != string::npos) {
return 0;
}
return 1 + vowelA(word.substr(found));
}
int vowelE (string word)
{
string str (word);
size_t found = str.find_first_of("e");
if (found != string::npos) {
return 0;
}
return 1 + vowelE(word.substr(found));
}
int vowelI (string word)
{
string str (word);
size_t found = str.find_first_of("i");
if (found != string::npos) {
return 0;
}
return 1 + vowelI(word.substr(found));
}
int vowelO (string word)
{
string str (word);
size_t found = str.find_first_of("o");
if (found != string::npos) {
return 0;
}
return 1 + vowelO(word.substr(found));
}
int vowelU (string word)
{
string str (word);
size_t found = str.find_first_of("u");
if (found != string::npos) {
return 0;
}
return 1 + vowelU(word.substr(found));
}
int main()
{
int number;
string word;
cout << " type in word ";
cin >> word;
number = vowelA(word) + vowelE(word) + vowelI(word) + vowelO(word) + vowelU(word);
cout << "total number of vowels in this word is " << number << endl;
system("pause");
return 0;
}
This program is in C++ and im getting weird errors when I run the program
Explanation / Answer
#include
#include
using namespace std;
int vowels( char *, int);
bool isVowel(char);
int main()
{
string array;
cout<<"Enter a string: ";
getline(cin,array);
cout << "The are "<< vowels( array.c_str(), 0) << " vowels in ""<<<"" ";
system("pause");
return 0;
}
int vowels( char *str, int subscript)
{
if (str[subscript] == '')
{
return 0;
}
else
if (isVowel(str[subscript]) )
{
return 1+vowels( str,subscript+1);
}
else
{
return vowels( str, subscript+1);
}
}
bool isVowel(char in)
{
switch(in)
{ case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U': return true;
}
return false;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.