Backbencher.dev

Printing Numbers Algorithm

Last updated on 27 May, 2020

Question

Write a function printNumbers(x, y) that prints numbers from x to y. x is less than y. Also, no loops can be used. ie, loops like while, for etc cannot be used in the code.

Example: Executing printNumbers(2, 5) prints 2, 3, 4, 5 in console.

Solution

function printNumbers(x, y) {
  if (x > y) return;
  console.log(x);
  printNumbers(x + 1, y);
}
--- ○ ---
Joby Joseph
Web Architect