Reputation: 43
I am writing a function that returns the number of vowels for a given string, here is the code:
int isVowel(string sequence)
{
int numberOfVowels = 0; //Initialize number of vowels to zero
string vowels = "aeiouAEIOU"; //Possible vowels, including capitals
for (int i = 0; i <= sequence.length(); i++)
{
for (int j = 0; j <= vowels.length(); j++)
{
if (sequence[i] == vowels[j])
{
numberOfVowels += 1;
}
}
}
return numberOfVowels;
}
This returns answers that are off by one. For example, input of "a" returns 2, input of "aa" returns 3, etc.
Upvotes: 0
Views: 1002
Reputation: 83557
i <= sequence.length()
<=
is almost never correct in any for loop since C++ uses 0-based indices. Instead, you should do
i < sequence.length()
Upvotes: 4