In: Computer Science
C++
Write a recursive function that computes and returns the product of the first n >=1 real numbers in an array.
#include <iostream> using namespace std; int getProduct(int arr[], int size, int start, int n){ if(n==0){ return 1; } else{ if(start < size){ if(arr[start]>=1){ return arr[start]*getProduct(arr,size,start+1,n-1); } else{ return getProduct(arr,size,start+1,n); } } } } int main() { int arr[] = {1,-2,3,4,-5,-6,7,-8,9,10}; cout<<getProduct(arr, 10, 0, 3)<<endl; return 0; }
12
int getProduct(int arr[], int size, int start, int n){ if(n==0){ return 1; } else{ if(start < size){ if(arr[start]>=1){ return arr[start]*getProduct(arr,size,start+1,n-1); } else{ return getProduct(arr,size,start+1,n); } } } }