# 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.

### 2 responses to “Sum of elements in an array using recursion in C++”

1. Omar Diab says:

Thanks for the example. Would be better if you explained how the function itself looks. I know most of it can be easily understood by glancing at the code, but I think it would be better to at least explain how “array+1” works. Not everyone has a great understanding of pointers so the statement seems kind of confusing at first. I think that would make the explanation more beginner-friendly.

• Saruque Ahamed Mollick says:

Thanks for your suggestion, we will be updating our content.