Sum of Even Numbers of an Array using Recursive Approach
This method solves the problem by using recursion. It defines a function that accepts three parameters: the array, the current index, and the sum of the total. After checking that the array has ended in the base case, the function calls itself recursively with the next element and, if the current number is even, changes the total.
Example: Recursive function `sumOfEvenNumbers` computes the sum of even numbers in an array. It recursively processes the array, adding even numbers to the sum. The base case returns 0 if the array is empty.
Javascript
function sumOfEvenNumbers(arr) { // Base case: If the array is empty, return 0. if (arr.length === 0) { return 0; } const firstElement = arr[0]; const restOfArray = arr.slice(1); if (firstElement % 2 === 0) { return firstElement + sumOfEvenNumbers(restOfArray); } else { return sumOfEvenNumbers(restOfArray); } } const numbers = [1, 2, 3, 4, 5, 6]; const evenSum = sumOfEvenNumbers(numbers); console.log( "Sum of even numbers:" , evenSum); |
Sum of even numbers: 12
JavaScript Program to Find Sum of Even Numbers of an Array
In JavaScript, working with arrays is a basic operation. We have to sum all the even numbers present in the array. We can check the number if it is even or not by the use of the % operator.
These are the following ways to find the sum of Even numbers in an Array:
Table of Content
- Iterative Approach
- Using filter() and reduce() methods
- Recursive Approach
- Using forEach Loop