Sum of even numbers up to using recursive function in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We have to write a recursive function that takes in a number n and returns the sum of all even numbers up to n.

Let’s write the code for this function −

Example

const recursiveEvenSum = (num, sum = 0) => {
   num = num % 2 === 0 ? num : num - 1;
   if(num){
      return recursiveEvenSum(num - 2, sum+num);
   }
   return sum;
};
console.log(recursiveEvenSum(12));
console.log(recursiveEvenSum(122));
console.log(recursiveEvenSum(23));
console.log(recursiveEvenSum(10));
console.log(recursiveEvenSum(19));

Output

The output in the console will be −

42
3782
132
30
90
raja
Published on 21-Aug-2020 14:31:03
Advertisements