Open In App

JavaScript Program to Print 1 to N using Recursion

In this article, we will see how to print 1 to N using Recursion in JavaScript.

What is Recursion? 

The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. In the recursive program, the solution to the base case is provided and the solution to the bigger problem is expressed in terms of smaller problems. 



Examples:

Input : 5
Output : 1 2 3 4 5

Input : 10
Output : 1 2 3 4 5 6 7 8 9 10

Approach:

 



Example: In this example, we will print 1 to N using Recursion in JavaScript.




function printRecursiveNum(num,currentValue) {
    if (currentValue>num) {
        return;
    }
    console.log(currentValue);
    printRecursiveNum(num, currentValue + 1);
}
  
const num = 8;
printRecursiveNum(num,1);

Output
1
2
3
4
5
6
7
8

Time Complexity: O(N)

Space Complexity: O(N)

Article Tags :