Write a recursive method “int sumPos(int a[], int n)” to calculate the sum of positive integers in an array of n integers, a[].
No global variables are allowed. No other method is allowed to be called by sumPos() except itself. (Hint: The integers in an array a[] of n integers are stored in a[0], a[1], ... a[n-1].)
int sumPos(int a[],int n){
if(n<0)
return 0;//return 0 if array has no elements left
else if(a[n-1]>0)
return a[n-1]+sumPos(a,n-1);//if positive element add it and call
function for other elements
else
return sumPos(a,n-1);//if negative number, do not add it
}
Explanation:
The above code uses recursion.
The n represents the number of elements.
So, the array addition od positive numbers starts from the last index of array.
If the element is positive then the element must be added and the recursive call must be made on the remaining elements.
If the element is negative then the element must not be added and the recursive call must be made on the remaining elements.
Get Answers For Free
Most questions answered within 1 hours.