mustafaSarialp - 1 year ago 85
C Question

# Count the number of vowels in a string

I simply want to count vowels in a string using recursion, but it doesn't work.

``````#include <stdio.h>
#include <string.h>

#define SETSIZ 10

#define TRUE 1
#define FALSE 0
int is_empty(const char *set);
int is_element(char vowel, const char *set);
int is_vowel(const char *vowels, const char *set);

int main(void)
{
int count = 0,i;
char vowels[11] = {'A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U', 'u', '\0'}, set[SETSIZ] = "mustafa";
for(i=0;i<strlen(set);i++){
if(is_vowel(vowels, set))
count +=  1;
}
printf("%s has %d vowels",set, count);
return(0);
}
int is_empty(const char *set)
{
return(set[0] == '\0');
}
int is_element(char vowel, const char *set)
{
int ans;
if(is_empty(set))
ans = FALSE;
else if (vowel == set[0])
ans = TRUE;
else
ans = is_element(vowel, &set[1]);
return(ans);
}
int is_vowel(const char *vowels, const char *set)
{
int ans, i = 0;

if(is_empty(vowels))
ans = FALSE;
else if(is_element(vowels[0], set))
{
printf("**");
ans = TRUE;
}
else
{
printf("--");
ans = is_vowel(&vowels[1], set);
}

return(ans);
}
``````

1. You do not loop through `set` as you probably want. Should be:

``````if(is_vowel(vowels, &set[i]))
``````
2. Your function `is_element()` is absolutely wrong, You can change it to:

``````int is_element(char vowel, const char *set)
{
return (vowel == set[0]);
}
``````

or even pass characters instead of pointers to characters.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download