Write a recursive, int -valued function named productOfOdds that accepts an inte
ID: 3817441 • Letter: W
Question
Write a recursive, int -valued function named productOfOdds that accepts an integer array , and the number of elements in the array and returns the product of the odd-valued elements of the array . You may assume the array has at least one odd-valued element . The product of the odd-valued elements of an integer -valued array recursively may be calculated as follows:
If the array has a single element and it is odd, return the value of that element ; otherwise return 1.
(in c++)
Otherwise, if the first element of the array is odd, return the product of that element and the result of finding the product of the odd elements of the rest of the array ; if the first element is NOT odd, simply return the result of finding the product of the odd elements of the rest of the array
Explanation / Answer
#include<iostream>
using namespace std;
int productOfOdds(int anArray[], int n);
int main()
{
int myArray[5] = {2};
cout << "The product of the odd array elements of Array is "<<productOfOdds(myArray,5)<<endl;
return 0;
}
int productOfOdds(int anArray[], int n)
{
if(anArray[n-1]%2){
if (n == 1 ) //odd and 1 number return that number
return anArray[n-1];
else
return anArray[n-1] * productOfOdds(anArray, n - 1);
}else{
if(n == 1 ) //if one element and is not odd return 1
return 1;
else
return productOfOdds(anArray, n - 1);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.