C++ Recursion C++ Recursion Recursion Write a function called arraySum(int[], in
ID: 666264 • Letter: C
Question
C++ Recursion
C++ Recursion Recursion Write a function called arraySum(int[], int) that accepts two arguments, an array of integers and a number indicating the number of elements in the array. The function should recursively calculate the sum of all the elements in the array. Demonstrate the use of the function in a program that asks the user to determine the array size and enter an array of integers. Then the program calls the arraySum function and prints the sum of all array elements. The following is a demo output from the programExplanation / Answer
Please find below the PROGRAM code with explanation.
/*
Program to Recursively find sum of array elements.
EXPLANATION of FLOW OF PROGRAM ( INPUTS, OUTPUTS )
1). The first input that the Program takes is the `NUMBER OF ELEMENTS TO BE SUMMED UP( `n` here )`
cout<<"How many integers you want to add up? "; cin>>n;
2). The second input that the Program takes is the `n` INTEGERS OF ARRAY
for(i=0; i<n; i++) cin>>arr[i]; sum1 = arraySum(arr,n);
3). The third step in the flow is the function call to Sum the Integers of Array.
sum1 = arraySum(arr,n);
Input/Output for the Function arraySum(int[], int) :
Inputs : (1)the Array (2) Current size of array OR next element from the last, which is to be summed up
Output : Sum of all the elements of the array
for example:
if array = {1,2,3,4,5}
then the function-call(s) & runtime-STACK is this:
sum = arraySum(A,5) -- initial function call
= array[4] + arraySum(A,4) -- first recursive call
= array[4] + array[3] + arraySum(A,3) -- second recursive call
= array[4] + array[3] + array[2] + arraySum(A,2) -- third recursive call
= array[4] + array[3] + array[2] + array[1] + arraySum(A,1) -- fourth recursive call
sum = array[4] + array[3] + array[2] + array[1] + array[0] -- fifth recursive call. This call hits the `Exiting condition check`.
*/
#include<cstdio>
#include<iostream>
using namespace std;
int arraySum(int array[],int n)
{
if(n==1)return array[n-1]; /* Exiting condition check */
else return (array[n-1] + arraySum(array,n-1)); /* recursively call the function with `current array size - 1` */
}
int main()
{
int n,i,sum1;
/* Take the size of array as input */
cout<<"How many integers you want to add up? "; cin>>n;
/* Declare integer array of size `n` */
int arr[n];
/* Input `n` array elements */
for(i=0; i<n; i++) cin>>arr[i];
/* Function call to the sum the Integers of Array */
sum1 = arraySum(arr,n);
cout<<" The sum is : "<<sum1;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.