0
I’m studying a little recursive function and I came across an exercise that’s taking my sleep, because it’s a basic exercise and I don’t understand the way out. Basically the book asks to create a function to test whether a number is PAR or not, returning a boleano value. But the function would have to meet the following requirements.
se o valor passado for 0 return true
se o valor passado for 1 return false
para qualquer outro valor faça n - 2 ate reduzi-lo a 0 ou 1.
my job was like this:
function epar(x){
if(x==0){
return true
}
else if(x==1){
return false
}
else{
epar(x-2)
}
}
console.log(epar('parametro'))
What they don’t understand is that when I put some value other than 1 or 0, it returns a Undefined value. I did some tests for example printing the value passed each time I returned the function and actually the value decreases as I would like, but for some reason it tao ta returning neither true nor false.
you have to give
return
in thatepar(x-2)
, otherwise the function returns nothing in this recursive cycle.– Sergio
You need to return the value, within the
else
must bereturn epar(x-2)
. And since this function only works with numbers, it doesn’t make sense to call by passing a string, so it should be something likeconsole.log(epar(5))
(step 5 or any other paragraph, as it makes no sense to pass the text'parametro'
if she only works with numbers)– hkotsubo
I understand, thank you very much, this value ai ta a string so to illustrate that would be passing any parameter, I was passing numbers, I will test with the thank you Return
– Alexandre Ramos