First, the int
return of the escrevevogais
function is useless. Therefore, you may want to change to void
.
Second, do not use gets
. I'll talk more about this in these other answers: 1 , #
Third, with each recursive call, it is necessary to advance a letter in the word. That way, the deeper the recursion, the further away from the beginning of the string you are. This means that with each recursive call, i
must be increased by 1. However, you were decreasing rather than increasing. The word never changes, so the first parameter is always the same.
Fourth, you can put the recursion before or after checking if the letter is a vowel:
-
If you put the recursion after verifying the letter, it will visit the letters one by one by going to the end of the string, stacking the recursive calls and then unmasking all the calls in reverse order, and as a result, the letters will appear in the order.
-
If you put the recursion before verifying the letter, it will stack the recursive calls to the end and as you uncrow them in reverse order, visit the letters in reverse order as well.
li>
So you should put the recursion before verifying the letter.
Fifth, the first position of the string is zero. This means that giving return
when i
is zero is not the right approach.
Sixth, to write entire strings, use "%s"
in printf
. To write isolated characters within strings, use "%c"
. The variable s
is a sstring, so s[i]
is an isolated character and must be written with "%c"
.
I see that the main problem in your attempt is that you considered that i
is decreasing from strlen(s)
to zero, and the approach shown by the given examples is the opposite, i
is growing until arrive at the end of the string (where there is the null terminator).
Considering all this, your code should look like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void escrevevogais(char s[50], int i) {
if (s[i] == 0) return;
escrevevogais(s, i + 1);
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u') {
printf("%c", s[i]);
}
}
int main() {
char s[50];
fgets(s, 50, stdin);
escrevevogais(s, 0);
}
The program does not consider uppercase vowels, but this is easy to fix.
See here working on ideone.