Horje
JavaScript Program to Print N to 1 using Recursion

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)



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
JavaScript Program to Check for Palindrome Number JavaScript Program to Check for Palindrome Number
JavaScript Count Distinct Occurrences as a Subsequence JavaScript Count Distinct Occurrences as a Subsequence
JavaScript Program to find Lexicographically next String JavaScript Program to find Lexicographically next String
How does Array.prototype.slice.call work in JavaScript ? How does Array.prototype.slice.call work in JavaScript ?
JavaScript URLify a given string (Replace spaces is %20) JavaScript URLify a given string (Replace spaces is %20)

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13