Recursion with an Array; can't get the right value to return

Posted by Matt on Stack Overflow See other posts from Stack Overflow or by Matt
Published on 2010-03-16T16:44:38Z Indexed on 2010/03/16 16:51 UTC
Read the original article Hit count: 306

Filed under:
|
|
|
|

Recursive Solution: Not working! Explanation: An integer, time, is passed into the function. It's then used to provide an end to the FOR statement (counter<time). The IF section (time == 0) provides a base case where the recursion should terminate, returning 0. The ELSE section is where the recursive call occurs: total is a private variable defined in the header file, elsewhere. It's initialized to 0 in a constructor, elsewhere. The function calls itself, recursively, adding productsAndSales[time-1][0] to total, again, and again, until the base call. Then the total is returned, and printed out later. Well, that's what I hoped for anyway.

What I imagined would happen is that I would add up all the values in this one column of the array and the value would get returned, and printed out. Instead if returns 0. If I set the IF section to "return 1", I noticed that it returns powers of 2, for whatever value time is. EG: Time = 3, it returns 2*2 + 1. If time = 5, it returns 2*2*2*2 + 1.

I don't understand why it's not returning the value I'm expecting.

int CompanySales::calcTotals( int time )
{
  cout << setw( 4 );
  if ( time == 0 )
   {
    return 0;
   }
  else
   {
    return total += calcTotals( productsAndSales[ time-1 ][ 0 ]);
   }
}

Iterative Solution: Working! Explanation: An integer, time, is passed into the function. It's then used to provide an end to the FOR statement (counter<time). The FOR statement cycles through an array, adding all of the values in one column together. The value is then returned (and elsewhere in the program, printed out). Works perfectly.

int CompanySales::calcTotals( int time )
{
 int total = 0;
 cout << setw( 4 );

 for ( int counter = 0; counter < time; counter++ )
 {
  total += productsAndSales[counter][0];
 }
 return total0;
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about array