Question: Write a function that accepts two arguments, an array of integers and a number indicating the number of elements in the array. The function should
Write a function 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 numbers in the array. Demonstrate the use of the function in a program that asks the user to enter an array of numbers and prints its sum.
this is what I got: but it wont work. Please give me the answer I have tried everything!
#include "stdafx.h"
#include
#include
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
/* Function call to the sum the Integers of Array */
sum1 = arraySum(arr, n);
cout << " The sum is : " << sum1;
return 0;
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
