First, the int
function return escrevevogais
is of no use. Therefore, it is convenient to change to void
.
Second, don’t use gets
. I talk more about it in these other answers: 1, 2 and 3.
Third, with each recursive call, it is necessary to advance a letter in the word. This way, the deeper the recursion, the further away from the beginning of the string you are. This means that with each recursive call, the i
has to be augmented in 1. However, you were decreasing rather than increasing. The word never changes, and therefore 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 place the recursion after checking the letter, it will visit the letters one by one going to the end of the string, stacking the recursive calls and then pop all the calls in reverse order, and as a result, the letters will appear in order.
If you put the recursion before the letter check, it will stack the recursive calls until the end and as it pops them in reverse order, visit the letters in reverse order as well.
Therefore, you must put the recursion before checking the letter.
Fifth, the first position of the string is zero. That means giving a return
when i
is not the right approach.
Sixth, to write whole strings, use "%s"
in the printf
. To write isolated characters within strings, use the "%c"
. The variable s
is an sstring, therefore s[i]
is an isolated caaractere and should be written with "%c"
.
I see the main problem in your attempt is that you’ve considered that the i
is decreasing from strlen(s)
up to zero, and the approach evidenced by the examples given is the opposite, the i
grows until you reach 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 tidy up.
See here working on ideone.