I have never been good at thinking recursively - when studying JAVA, C and now again studying C++. Not that I am good at anything right now as a student but, I have tripped over it every time. It is assigned again, and I have to do it.
There were three assignments. The first was drawing a picture of stars. I got through that with great difficulty, and now I am tripping myself up with the next two and confusing the beegeebers out of myself. They are:
1. Writing a recursive function, vowels, that returns the number of vowels in a string, then write a program to test the function.
2. Write a recursive function to check whether a string is a palindrome or not. The function returns true or false and I can't use any global variables.
Focusing on the first, I can do it with a for loop checking each position in the string if it matches a vowel in caps or lower case and incrementing a counter if it does, otherwise just moving to the next position but recursively ...not.
I have an algorithm that:
1. asks for a string.
2. sends the string to the function (I think i need to send a pointer, too)
3. checks the first string position against the list of vowels
4. if found increment counter, move to next position
if not just move to next position
5. repeat 4 until end of string is reached
6. return counter
But, how do I put this into a recursive function???
My main looks like:
Code:
#include <iostream>
#include <string>
using namespace std;
void displayBanner();
int vowels(string phrase, int count);
int main()
{
int ptr = 0;
displayBanner();
cout << "Enter a phrase: ";
string phrase;
getline(cin, phrase);
cout << "\nThe phrase you entered: " << phrase << endl;
cout << "\nhas " << vowels(phrase, ptr) << " vowels." << endl;
return 0;
}
void displayBanner()
{
cout << "This programs asks for you to enter a string.\n"
<< "it then calculates how many vowels it contains\n"
<< "using a recursive function.\n\n";
}
and so far my recursive functio is a mess, but is:
Code:
int vowels(string phrase, int *ptr)
{
while (phrase[i] != '\n')
{
if (phrase[i] == 'a'
|| phrase[i] == 'e'
|| phrase[i] == 'i'
|| phrase[i] == 'o'
|| phrase[i] == 'u'
|| phrase[i] == 'A'
|| phrase[i] == 'E'
|| phrase[i] == 'I'
|| phrase[i] == 'O'
|| phrase[i] == 'U')
count++;
vowels[i + 1];
}
return count;
}
Am I moving it the right direction, or do I need to scrap the function and rethink everything?
By the way, I search this board for help before posting and I couldn't find anything that helped me.
Thanks for the help ALL.