Sum of elements in an array using recursion in C++

In this tutorial, you will learn how to write the code to find the sum of elements in an array using recursion in C++. There are different ways of solving the problem using the recursion and without using the recursion. In this problem, we solve it using recursive functions to find the sum of elements of an array.

Program to find the sum of elements in an array using recursion in C++

In the program, we use the header file iostream. And then we write the code. we declare an array and name it, then initialize it with some integers. we pass that array element to the function to find the sum of all elements in an array.

#include<iostream>
using namespace std;
int sum(int n,int array[]){
    if(n==0){
        return 0;
    }
    if(n==1){
        return array[0];
    }
    if(n>1){
    int k {};
    k=array[0]+sum(n-1,array+1);
    return k;
    }
}
int main(){
    int array[]={5,2,3,3,4};
    int arraysize= sizeof(array)/sizeof(array[0]); // gives the array size.
    int output = sum(arraysize,array);
    cout<<output;
}

Code Explanation:

  1. In the program, we use the header file iostream. And then we write the code. we declare an array and name it(array here), then initialize it with some integers(5,2,3,3,4) and also determine the size of the array. we pass that array element to the function to find the sum of all elements in an array.
  2. We need to find the size of the array, and for that, we use sizeof() function. After finding the size, we pass the array along with the array size to the function.
  3. After passing into the function it finally returns the sum of the integers in an array. In the above code, the sum of elements in an array is equal to 17.

The output of the code is:

17

I hope you understand how to find the sum of the elements in an array using recursion.

Also read: How to sort an array using recursion in C++

Leave a Reply

Your email address will not be published. Required fields are marked *