Reputation: 13
I have a homework in which I'm given a code that is supposed to count the number of vowels in a string. Pieces of the code are missing and I have to fill it in. However I can't for the life of me figure out how to do it. I could easily count the vowels with a for loop, but this homework is very restrictive and I don't know how to make this program work this way. Here's the code:
#include <stdio.h>
int vowels(char *s)
{
char *z ="aeiouy";
int count = /-/;
while (/-/)
count+= /-/
if (/-/)
return 0;
return count;
}
int main()
{
char buf (/-/);
while (scanf("%s", buf)>0)
printf("%d\n", vowels(buf));
return 0;
}
The /-/ are the areas I'm supposed to fill in to make the program work. The while loop in function vowels is giving me the most trouble, I have absolutely no idea what to put there. Here's what I've got so far.
#include <stdio.h>
int vowels(char *s)
{
char *z ="aeiouy";
int count = 0;
while (/-/)
count+= 1
if (count==0)
return 0;
return count;
}
int main()
{
char buf [1000];
while (scanf("%s", buf)>0)
printf("%d\n", vowels(buf));
return 0;
}
I understand that "recursively" means that I should call the function inside its body, but I don't understand how to do it in this program. Please help!
EDIT: "Write a recursive function vowels() which returns a number of vowels in a string." That's the assignment I got. The first code I submitted is the one I got from the professors, I can't change it in any way, I am only allowed to fill in the blanks (/-/). The second code I submitted is what I think should be in the blanks, it's probably not correct though.
EDIT2: Another thing I forgot to mention, the lines can be in the wrong order, I'm supposed to put it and the right order and fill in the blanks. I think the order I submitted is correct but I might be wrong.
Upvotes: 1
Views: 183
Reputation: 311048
The function you presented does not have a recursion. Moreover it is declared incorrectly. At least the parameter shall have the qualifier const
because the passed string is not changed within the function.
Taking into account your requirements to the function (a while loop and an array) the function can be defined the following way as it is shown in the demonstrative program
#include <stdio.h>
size_t vowels( const char *s )
{
if ( !*s ) return 0;
const char *z = "aeiouy";
size_t count = 0;
while ( z[count] != '\0' && z[count] != *s ) ++count;
return ( z[count] != '\0' ) + vowels( s + 1 );
}
int main(void)
{
const char *s = "Hello TommySVK";
printf( "There are %zu vowels in the string \"%s\"\n",
vowels( s ), s );
return 0;
}
The program output is
There are 4 vowels in the string "Hello TommySVK"
If you need you may substitute the type size_t
used in the function for the type int
and the expression ++count
for count += 1
.
Upvotes: 1