In: Computer Science
please write in c++
2. Write a function sumOfArray that recursively finds the sum of a one-dimensional array. A sample run is below.
The elements of the array are: 0 8 -4 6 7 The sum of the array is: 17 Press any key to continue . . . |
Recursion:
The recursive function calls to itself and a terminate or base condition is specified which breaks the infinite execution of the recursive call. When the function call to itself then it works like a continue statement and the control goes to the starting of the function with updated argument value.
The stack data structure is used in recursion for storing the intermediate value when each function call is made.
In a recursive function, two cases are mentioned:
Base condition:
A terminate condition or base condition is specified which breaks the infinite execution of the recursive call.
Recursive Call:
The function will call to itself and this is known as a recursive call.
The required program source code is given below:
#include <iostream>
using namespace std;
//function to find the sum of the array recursively
int sumOfArray(int arr[], int size)
{
//base condition
if(size<1)
return 0;
else
{
//recursive call
return arr[size-1] + sumOfArray(arr, size-1);
}
}
int main()
{
//array declaration and initialization
int arr[] = {0, 8, -4, 6, 7};
//function calling and display result
cout<<sumOfArray(arr, 5);
return 0;
}
OUTPUT:
17