I'm having trouble getting a recursion template reduceArray() function to divided elements in an array. I have +,-, and * working fine, but division is not working for me. The function should take the given elements and divide as follows ((((4/2)/7)/1)/9)

Here's my code...any tips?

#include<iostream> 
using namespace std;

template<typename T>
T reduceArray(T myArray[], int size, char op)
{
    if(size < 0 && op == '/')
        return 1;
    else
        if(size == 0)
            return myArray[size]/reduceArray(myArray, size-1, op);
        else
            return reduceArray(myArray, size-1, op)/myArray[size];
}

int main()
{
    int ARRAY_CAP = 5;
    int intArray[] = {4,2,7,1,9};  // +23 -15 *504 /.0317460317
    char op;
    cout << "Enter +,-,*, or / to perform one of the mathematical operations on an array of ints: ";
    cin >> op;
    
    cout << reduceArray(intArray, ARRAY_CAP-1, op) << endl;
    
    system("pause");
    return 0;
}

Sorry, but can you please explain your program cause at my system it is not working for any of +,- or *. The program is not using the operator anywhere...

Just for division:

template<typename T>
T reduceArray(T myArray[], int size)
{
    if (size == 0)
        return myArray[0];
    return reduceArray(myArray, size - 1) / myArray[size];
}

Your code is working very well...............
whats your accepted output.
Your Program give 0 on when your element is

int intArray[] = {4,2,7,1,9};

which is like this which you mention in your problem that means you know the concept of.....

Expleanation of your code

step 1. ((((4/2)/7)/1)/9)
step 2. (((2/7)/1)/9)
step 3. ((0/1)/9)
step 4. (0/9)
step 5. 0

and your give the same result (0)

try this you will get 5

intArray[] = {80,2,2,2,2};

I hope you understand now

Best Of Luck.

Thanks a bunch, i didnt realize since it was a template function that it would return the int instead of the double. Got it now!

Your code is working very well...............
whats your accepted output.
Your Program give 0 on when your element is

int intArray[] = {4,2,7,1,9};

which is like this which you mention in your problem that means you know the concept of.....

Expleanation of your code

step 1. ((((4/2)/7)/1)/9)
step 2. (((2/7)/1)/9)
step 3. ((0/1)/9)
step 4. (0/9)
step 5. 0

and your give the same result (0)

try this you will get 5

intArray[] = {80,2,2,2,2};

I hope you understand now

Best Of Luck.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.