vowel count with recursion

I can't get this to work properly. There is a runtime error that I can't seem to get around. What's going on here...
Write a recursive function int vowels(string s) that receives a string and returns the number of vowels in the string


1
2
3
4
5
6
7
8
9
10
11
12
13
14
int vowel(string s)
{
  int count = 0;
  char ch;
  if (s.length() == 1)
  {
    if ((ch == 'a')||(ch == 'e')||(ch == 'i')||(ch == 'o')||(ch == 'u')
       count++;
  }
  else
    count += vowel(s);

  return count;
}

Last edited on
You are using the variable 'ch' uninitialized. You should initialize variables before using them.

What exactly are you trying to do with this:
if ((ch == 'a')||(ch == 'e')||(ch == 'i')||(ch == 'o')||(ch == 'u')
anyway, given that you never put a value into the variable 'ch'. Perhaps you want to iterate through the string and set 'ch' equal to each character of your string 's' in turn.

Also, at the end of this line (line 7), you are missing a bracket, I believe.

Regards
-Xander314
This isn't a recursive function since a recursive function calls it self until a end (in this case the end of the string)
How could I rearrange this to be recursive?
Well the function needs to call itself. Of course, the key to the problem is working out what argument to call the function with, and realising and implementing a means of stopping in the end.

At a guess, you will have to remove one character each time, whereas at present you just call it again with the same string, so that it will loop forever.
that would explain the stack overflow lol
Lol, yes it would :P Always make sure you're recursive functions terminate the recursive descent at some point :)
Topic archived. No new replies allowed.