In: Computer Science
Using C++: Write a function that recursively calculates the sum of an array. The function should have 2 parameters, the array and an integer showing the number of elements (assume they are all integers) in the array. The function will use a recursive call to sum the value of all elements.
You must prompt for a series of integers to be entered in the array. As your program reads the numbers in, increment a count so it knows how many elements the array has. Use a symbol for users to indicate when they are done with entering numbers (choose any letter you think is proper, but you need to print it on screen at the beginning to let users know which one to enter). Then your program will print the sum of the array elements on the screen.
#include<iostream>
#include <stdlib.h>
using namespace std;
int sumArray(int arr[], int size) {
int sum = 0;
if(size > 0)
sum +=
arr[size-1]+sumArray(arr,size-1);
else
return sum;
}
int main() {
int randArray[500];
int num = 0;
int count = 0;
cout << "Enter a number: (Enter any non-numeric
character to quit)" <<endl;
while(cin >> num) {
randArray[count] = num;
count++;
cout << "Enter a number:
(Enter any non-numeric character to quit)" <<endl;
};
int sum = sumArray(randArray, count);
cout <<"Sum: " << sum << endl;
}
------------output-----------------
Enter a number: (Enter any non-numeric character to quit)
1
Enter a number: (Enter any non-numeric character to quit)
2
Enter a number: (Enter any non-numeric character to quit)
-1
Enter a number: (Enter any non-numeric character to quit)
-2
Enter a number: (Enter any non-numeric character to quit)
q
Sum: 0