Categories

6 Problems of Recursion in Javascript with Solution

 In this article I am going to mention 6 Javascript Recursion examples.

How Recursion works.

It basically works by calling same function again and again until it reaches a base case that is usually an if condition and from here it returns.

This example includes following things.

  1. Calculate Factorial of a Number
  2. Print Increasing Decreasing using Recursion 
  3. Sum of N numbers using Recursion
  4. Reverse an array using Recursion
  5. Check if Number is Palindrome 

// Calculate Factorial of a Number e.g 5 ! = 5x4x3x2x1

function findFactorial(n){
    if(n==0){
        return 1;
    }    
  return  findFactorial(n-1) *n;  
}


findFactorial(5);



//  Print Increasing Decreasing e.g 3 2 1 1 2 3
function IncresingDecreasing(n){ if(n<1){ return; } console.log(n) IncresingDecreasing(n-1); console.log(n) } IncresingDecreasing(5); // Sum of N numbers e.g 1 + 2 + 3 + 4 = 10 function sumOfNumbrs(n){ if(n==0){ return 0; } return n + sumOfNumbrs(n-1); } v=sumOfNumbrs(10000); console.log(v); // Reverse an array [1,2,3,4,5] to [5,4,3,2,1] function reverseArray(i,n,arr2=[]){ if(i <= 0){ return; } arr2.push(n[i-1]); reverseArray(i-1,n,arr2); return arr2; } z=reverseArray(15,[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]); console.log(z); // Check if number is Palindrome e.g 2002, Here we will reverse the digits and compare if
// equal then it is palindrome

function reverseDigit(n,arr=[]){

  if(n==0){
    return;
  }
  
  let num1 = n%10;
  let num2 = parseInt(n/10);
  arr.push(num1);
  
  checkIfNumberPalindrome(num2,arr);
  
  return arr;
  
}

function checkPalindrome(a){
  let reverseArr = reverseDigit(a,[]);
  let revedigit =parseInt(reverseArr.join(''));
  if(revedigit == a){
    return "It is Palindrome";
  }else{
    return "It is not a Palindrome"
  }
}

 let reverse = checkPalindrome(5465464654);
console.log(reverse);
adbanner