Open In App

JavaScript Program to Print N to 1 using Recursion

Last Updated : 13 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
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)


Print N to 1 using Recursion
Visit Course explore course icon

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy