Sum of even elements of an Array using Recursion
Given an array arr[] of integers, the task is to find the sum of even elements from the array.
Examples:
Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8}
Output: 20
2 + 4 + 6 + 8 = 20
Input: arr[] = {4, 1, 3, 6}
Output: 10
4 + 6 = 10
Approach: Write a recursive function that takes the array as an argument with the sum variable to store the sum and the index of the element that is under consideration. If the current element at the required index is even then added to the sum else do not update the sum and again call the same method for the next index. The termination condition will be when there is no element left to consider i.e. the passed index is out of the bounds of the given array, print the sum, and return in that case.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void SumOfEven( int arr[], int i, int sum)
{
if (i < 0) {
cout << sum;
return ;
}
if ((arr[i]) % 2 == 0) {
sum += (arr[i]);
}
SumOfEven(arr, i - 1, sum);
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int n = sizeof (arr) / sizeof (arr[0]);
int sum = 0;
SumOfEven(arr, n - 1, sum);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
static void SumOfEven( int arr[],
int i, int sum)
{
if (i < 0 )
{
System.out.print(sum);
return ;
}
if ((arr[i]) % 2 == 0 )
{
sum += (arr[i]);
}
SumOfEven(arr, i - 1 , sum);
}
public static void main (String[] args)
throws java.lang.Exception
{
int arr[] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 };
int n = arr.length;
int sum = 0 ;
SumOfEven(arr, n - 1 , sum);
}
}
|
Python3
def SumOfEven(arr, i, sum ):
if (i < 0 ):
print ( sum );
return ;
if ((arr[i]) % 2 = = 0 ):
sum + = (arr[i]);
SumOfEven(arr, i - 1 , sum );
if __name__ = = '__main__' :
arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ];
n = len (arr);
sum = 0 ;
SumOfEven(arr, n - 1 , sum );
|
C#
using System;
class GFG
{
static void SumOfEven( int []arr,
int i, int sum)
{
if (i < 0)
{
Console.Write(sum);
return ;
}
if ((arr[i]) % 2 == 0)
{
sum += (arr[i]);
}
SumOfEven(arr, i - 1, sum);
}
public static void Main (String[] args)
{
int []arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
int n = arr.Length;
int sum = 0;
SumOfEven(arr, n - 1, sum);
}
}
|
Javascript
<script>
function SumOfEven(arr,i,sum)
{
if (i < 0)
{
document.write(sum);
return ;
}
if ((arr[i]) % 2 == 0)
{
sum += (arr[i]);
}
SumOfEven(arr, i - 1, sum);
}
let arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
let n = arr.length;
let sum = 0;
SumOfEven(arr, n - 1, sum);
</script>
|
Time Complexity: O(n), where n is the size of the given array.
Auxiliary Space: O(n), due to recursive call stacks.
Last Updated :
19 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...