Note that there are some explanatory texts on larger screens.

plurals
  1. POSmall issue in recursive array program
    primarykey
    data
    text
    <p>I'm having a bit of trouble with a recursive function. I pass an array containing integers into it, an then the function either adds or subtracts them all together. I got the addition function implemented correctly, but I am having a hard time getting the subtraction bit correct. </p> <p>Here is what I've noticed: size is currently set to 5. To test it I change the if(i == size) line in the subtraction part of the function to if(i == (size - 3)), and it appears to subtract the second element correctly from the first element (4 - 2). But if I let it run again, I get 9, instead of (4-2) - 7 = -5, which I should get. Is it adding a -7, perhaps? </p> <p>Also, I am really grateful for all pointers, but I also acknowledge that this may not be the most efficient program to accomplish what I'm trying to do. I'm a beginning programmer, and it would help me most to see where I've gone wrong in my current program, as opposed to how I should have done my algorithm instead.</p> <pre><code>#include&lt;iostream&gt; using namespace std; int reduceArray(int array[], int size, char op, int i = 0) { if(op == '+') { if(size == 0) return 0; if(i == size) return 0; else { return array[i++] + reduceArray(array, size, '-', i + 1); } } else if(op == '-') { if(size == 0) return 0; if(i == (size - 2)) //changing this to "size - n" changes how many numbers are subtracted return 0; else { return array[i++] - reduceArray(array, size, '-', i + 1); } } } int main() { int array[] = {4, 2, 7, 1, 9}; //cout &lt;&lt; reduceArray(array, 5, '+') &lt;&lt; endl; this bit works fine works fine cout &lt;&lt; reduceArray(array, 5, '-') &lt;&lt; endl; system("pause"); return 0; } </code></pre> <p><strong>EDIT:</strong> Actually--the same thing happens for the division program. For the third element of the array (the 7), it is doing the INVERSE operation--when it should subtract, it adds, when it should divide, it multiplies--can't figure out why this is happening.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload