Sum Of Array Elements Using Recursion

Sum Of Array Elements Using Recursion

QUESTION DESCRIPTION :

Given an array of integer elements, find sum of array elements using recursion.

TEST CASE 1

INPUT

5
1 2 3 4 5

OUTPUT

15


TEST CASE 2

INPUT

4
4 4 4 4

OUTPUT

16

#include<iostream>
using namespace std;

int add(int arr[],int n){ // this is a recursive function that returns the sum of the array
 if(n>=0){
  return arr[n]+add(arr,n-1);  // if n>=0 i.e. a valid index we return 
        // the current array value to the old recursive call 
       // and then make another recursive call with a smaller n value (n-1)
 }
 else{
  return 0; // if all numbers have been added we return 0 and 
       // don't make any recursive call thus exiting the function
 }
} 

int main(){

 int n; // to store the number of inputs;
 cin>>n;

 int arr[n]; // to store the n numbers

 for(int i=0;i<n;i++){
  cin>>arr[i]; // taking the integers as input
 }
 
 cout<< add(arr,n-1); // directly printing the sum
 return 0;
}

Comments

Popular Posts