print all the multiples of 5 till n in a recursive way.
The output should be from 0 5 10 15 20 25..to n
function print_output(n){
if (n<0){
return;
}
if(n%5==0){
console.log(n);
}
return print_output( n-1);
}
The output of this code is n…25,20,15,10,5,0.
I want to get answer in the order of 0 to n
2
Answers
The function is recursively decreasing
n
to compare it against%5===0
.To reorder it, you have to use an array to push results into.
When
n < 0
, reorder the array and console log it.Without using an array as above, you still need to pass a second argument, which would be the starting number.
So now, the recursion will increase that starting number and compare it against
n
.Note: You also could pass a third argument that would be the modulo… 😉
Let’s call the argument you pass in
target
. You’ll need one more argument to pass the the function which we can callresult
. You can initialiseresult
to zero if the argument doesn’t exist.return
ifresult
>target
.5
.target
andresult
back toprint_output
making sure you increment the result by5
.