What is happening is that you are zeroing the value of m
with each iteration, so it will always return m=0
. An alternative is to make m
a function parameter, passed at each iteration. It would look like this:
#include <stdio.h>
int menor(int vet[], int i, int m) {
// Se tiver chegado já ao fim do array para o código
if(i < 0) {
return m;
}
// Verifica se o valor atual é menor que o MENOR valor salvo até então
if(vet[i] < m) {
m = vet[i];
}
// Chama a recursão
return menor(vet, i-1, m);
}
int main() {
int vetor[]= {8,2,3,5,7,11,13,17};
// Adicionamos um parâmetro na chamada, no caso o último valor do vetor.
int m = menor(vetor, 7, vetor[7]);
printf("%d\n",m);
return 0;
}
Notice that we start with a kick, which belongs to the vector, of the smallest value instead of starting with a predefined value. Could the way you did it lead to unexpected behaviors, for example, and if no value were less than 0? 0 would be returned and could not even belong to the searched vector.