Reputation: 265
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);
}
Upvotes: 1
Views: 1830
Reputation: 1
You can use this code in python to count the number of vowels:
def vowels( s ):
if s == '':
return 0 # no vowels in the empty string
elif s[0] in 'aeiouAEIOU':
return 1 + vowels( s[1:] )
else:
return 0 + vowels( s[1:] )
You can also use a variable such as vowel_list='aeiouAEIOU'
Upvotes: 0
Reputation: 3
#include <stdio.h>
int vowel(char str[],int k)
{
int count = 0;
while(str[k]!='\0')
{
if(str[k] == 'a' || str[k] == 'e' || str[k] == 'i' || str[k] == 'o' || str[k] == 'u')
return 1 + vowel(str,k+1);
else
return 0 +vowel(str,k+1);
}
return 0;
}
void main()
{
char x[50];
gets(x);
printf("%d",vowel(x,0));
}
Upvotes: 1
Reputation: 5736
You do not loop through set
as you probably want. Should be:
if(is_vowel(vowels, &set[i]))
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.
Upvotes: 0
Reputation: 108978
In main
, your for loop calls is_vowel()
several times with the exact same arguments.
You may want to rewrite the function with a simpler protoyype:
/* int is_vowel(const char *vowels, const char *set); */
int is_vowel(const char *vowels, int ch);
Upvotes: 1
Reputation: 5917
There is a simpler solution to your problem:
#define VOWELS "aeiouAEIOU"
size_t vcount(const char *s)
{
size_t i = 0;
while (s && *s) {
if (strchr(VOWELS, *s)) ++i;
++s;
}
return i;
}
It can easily be transformed into a recursive version.
Upvotes: 0
Reputation: 6695
There is problem in your is_vowel code.
int is_vowel(const char *vowels, const char *set)
{
int ans, i = 0;
if(is_empty(vowels)) //You are passing vowels which would never be empty.
ans = FALSE; //Replace it with set character pointer.
//Rest of the code
The whole concept,applied seems to be wrong buddy .I would suggest you to rewrite the code.There are myriad number of mistakes in the entire code.
Upvotes: 3