Problem statement:- Program to Find the sum of Odd numbers using recursion in an array.
Data requirement:-
Input Data:-n, arr
Output Data:-SumOfEvenElement(arr,n)
Output Data:-SumOfEvenElement(arr,n)
Program in C
Here is the source code of the C Program to Find the sum of Odd numbers using recursion in an array.
Code:
#include<stdio.h>
int SumOfOddElement(int arr[], int n)
{
static int sum=0;
int i;
if(n>0)
{
i=n-1;
if(arr[i]%2==1)
sum=sum+arr[i];
SumOfOddElement(arr,i);
}
return sum;
}
int main()
{
int n,j;
printf("Enter your array size:");
scanf("%d",&n);
int arr[n];
printf("Enter the Array Element:");
for(j=0;j<n;j++)
{
scanf("%d",&arr[j]);
}
printf("Sum of Odd Element is: %d",SumOfOddElement(arr,n));
}
Enter your array size:5
Enter the Array Element:4 8 10 3 5
Sum of Odd Element is: 8
Program in C++
Here is the source code of the C++ Program to Find the sum of Odd numbers using recursion in an array.
Code:
#include<iostream>
using namespace std;
int SumOfOddElement(int arr[], int n)
{
static int sum=0;
int i;
if(n>0)
{
i=n-1;
if(arr[i]%2==1)
sum=sum+arr[i];
SumOfOddElement(arr,i);
}
return sum;
}
int main()
{
int n,j;
cout<<"Enter your array size:";
cin>>n;
int arr[n];
cout<<"Enter the Array Element:";
for(j=0;j<n;j++)
{
cin>>arr[j];
}
cout<<"Sum of Odd Element is: "<<SumOfOddElement(arr,n);
}
Enter your array size:6
Enter the Array Element:9 13 55 65 100 2
Sum of Odd Element is: 142
Program in Java
Here is the source code of the Java Program to Find the sum of Odd numbers using recursion in an array.
Code:
import java.util.Scanner;
public class SumOddElement {
int sum=0;
int SumOfOddElement(int arr[], int n)
{
int i;
if(n>0)
{
i=n-1;
if(arr[i]%2==1)
sum=sum+arr[i];
SumOfOddElement(arr,i);
}
return sum;
}
public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
int n,i;
System.out.println("Enter your Array Size:");
n=cs.nextInt();
int arr[]=new int[n];
System.out.println("Enter the Array Element:");
for(i=0;i<n;i++)
{
arr[i]=cs.nextInt();
}
SumOddElement ob=new SumOddElement();
System.out.print("Sum of odd Element is:"+ob.SumOfOddElement(arr,n));
cs.close();
}
}
Enter your Array Size:
8
Enter the Array Element:
4 5 10 13 52 33 3 7
Sum of odd Element is:61
Program in Python
Here is the source code of the Python program to Find the sum of Odd numbers using recursion in an array.
Code:
sum=0
def SumOfOddElement(arr,n):
global sum
if(n>0):
i=n-1
if(arr[i]%2==1):
sum=sum+arr[i]
SumOfOddElement(arr,i)
return sum
arr=[]
n = int(input("Enter the size of the array: "))
print("Enter the Element of the array:")
for i in range(0,n):
num = int(input())
arr.append(num)
print("Sum of Odd Element is:",SumOfOddElement(arr,n))
Enter the size of the array: 4
Enter the Element of the array:
4
3
6
9
Sum of Odd Element is: 12
Most Recommend Questions:-
More Questions:-
0 Comments
Please do not Enter any spam link in the comment box