skip to Main Content

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


  1. 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.

    function print_output(n, result) {
      if (n < 0) {
        const orderedResults = result.sort((a, b) => a - b)
        orderedResults.forEach((r) => console.log(r))
        return
      }
      if (!Array.isArray(result)) {
        console.error('Second argument is not an array')
        return
      }
    
      if (n % 5 === 0) {
        result.push(n)
      }
      print_output(n - 1, result)
    }
    
    print_output(32, [])

    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.

    function print_output(a, n) {
      if (a > n) {
        return
      }
      if (a % 5 === 0) {
        console.log(a)
      }
      print_output(a + 1, n)
    }
    
    print_output(0, 32)

    Note: You also could pass a third argument that would be the modulo… 😉

    Login or Signup to reply.
  2. Let’s call the argument you pass in target. You’ll need one more argument to pass the the function which we can call result. You can initialise result to zero if the argument doesn’t exist.

    1. return if result > target.
    2. Log a number if it’s a multiple of 5.
    3. Pass both target and result back to print_output making sure you increment the result by 5.
    function print_output(target, result = 0) {
    
      if (result > target) return;
    
      if (result % 5 == 0) console.log(result);
    
      return print_output(target, result + 5);
    
    }
    
    print_output(99);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search