Open In App

JavaScript Program to Print 1 to N using Recursion

Last Updated : 26 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • We create a function that takes two arguments: “num” which is the number up to which we have to print and “currentValue” which prints the current number.
  • Check for the base case. Here it is currentValue > num.
  • If the base condition is satisfied, then it returns and ends the recursion.
  • If the base condition is not satisfied, print currentValue and call the function recursively by increasing the currentValue by 1 and num, until the base condition satisfies.

 

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

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)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads