Open In App

JavaScript Program to Print N to 1 using Recursion

Last Updated : 13 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to print N to 1 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 : N = 10 
Output : 10 9 8 7 6 5 4 3 2 1

Input : N = 7 
Output : 7 6 5 4 3 2 1   

Approach:

  • Check for the base case. Here it is num==0.
  • If the base condition is satisfied, then it returns and ends the recursion
  • If the base condition is not satisfied, print N and call the function recursively with value (N – 1) until the base condition satisfied.

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

Javascript




function printRecursiveNum(num) {
    if (num == 0) {
        return;
    }
    console.log(num);
    printRecursiveNum(num - 1);
}
  
const num = 8;
printRecursiveNum(num);


Output

8
7
6
5
4
3
2
1

Time Complexity: O(N)

Space Complexity: O(N)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads