Problem statement:- Program to the sum of elements in an array using recursion.
Data requirement:-
Input Data:-n, arr
Output Data:-SumOfArray(arr,n)
Output Data:-SumOfArray(arr,n)
Program in C
Here is the source code of the C Program to the sum of elements in an array using recursion.
Code:
#include<stdio.h>
int SumOfArray(int arr[], int n)
{
static int sum=0;
int i;
if(n>0)
{
i=n-1;
sum=sum+arr[i];
SumOfArray(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 Array Element is: %d",SumOfArray(arr,n));
}
Enter your array size:5
Enter the Array Element:4 8 10 3 5
Sum of Array Element is: 30
Program in C++
Here is the source code of the C++ Program to the sum of elements in an array using recursion.
Code:
#include<iostream>
using namespace std;
int SumOfArray(int arr[], int n)
{
static int sum=0;
int i;
if(n>0)
{
i=n-1;
sum=sum+arr[i];
SumOfArray(arr,i);
}
return sum;
}
int main()
{
int n,i;
cout<<"Enter your array size:";
cin>>n;
int arr[n];
cout<<"Enter the Array Element:";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"Sum of Array Element is:"<<SumOfArray(arr,n);
return 0;
}
Enter your array size:6
Enter the Array Element:9 13 55 65 100 2
Sum of Array Element is:244
Program in Java
Here is the source code of the Java Program to the sum of elements in an array using recursion.
Code:
import java.util.Scanner;
public class SumOfArrayElement {
int sum=0;
int SumOfArray(int arr[], int n)
{
int i;
if(n>0)
{
i=n-1;
sum=sum+arr[i];
SumOfArray(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();
}
SumOfArrayElement ob=new SumOfArrayElement();
System.out.print("Sum of Array Element is:"+ob.SumOfArray(arr,n));
cs.close();
}
}
Enter your Array Size:
8
Enter the Array Element:
4 5 10 13 52 33 3 7
Sum of Array Element is:127
Program in Python
Here is the source code of the Python program to the sum of elements in an array using recursion.
Code:
sum=0
def SumOfArray(arr,n):
global sum
if(n>0):
i=n-1
sum=sum+arr[i]
SumOfArray(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 Array Element is:",SumOfArray(arr,n))
Enter the size of the array: 3
Enter the Element of the array:
99
3
7
Sum of Array Element is: 109
Most Recommend Questions:-
More Questions:-
0 Comments
Please do not Enter any spam link in the comment box