Moderator emeritus

Maybe I'm saying something obvious... but your code doesn't really do much of anything. So how do you know it isn't just doing it and exiting happily? Main just runs the integerSummer and doesn't even do anything with the result. It doesn't take very long to calculate the result. So it seems like nothing happened. You should start by at least outputting / returning the result!

macrumors newbie

Well, for starters, are you outputting anything to the screen? Your program does the function calls, pauses, and then ends. No output to the screen at all.

Your recursive function, integerSummer, takes two arguments: a vector and an index into that vector. From your call, integerSummer(new_one, 3), I'm guessing you want to calculate the sum of the first 4 numbers: elements 3, 2, 1, 0?

If so, there's a slight problem: element 0 will always be zero. In your new_one vector, however, element 0 is 11. This is what the sum would look like: 17 + 21 + 20 + 0. That last number should have been an 11.

Moderator emeritus

Also, the code only sums the nth and n - 1 value of the vector. You need to loop over the vector and add them up (with a running total) n times.

Click to expand...

I might be dense and really I don't even know why I'm looking at code today... But I think this is not true. The core recursion idea is correct here -- main calls integerSummer at position 3. That call in turn calls integerSummer at position 2. That call in turn calls integerSummer at position 1. And then the last call returns a discrete value (0) which allows for the recursion to close and allows the right-hand-side value in this line calculated:

Code:

return temp + integerSummer(new_one, n - 1);

The issue of summing position zero aside, I think the recursion works....

Funny enough, in this case it actually works correct because you're exiting from the function on time in the n==0 case because of the return. But someday some case will pop up where it doesn't work correctly and it will take ages before you find the problem. I would recommend to always use brackets where you can, it makes the code much more clear to read and it avoids bugs.

macrumors 6502a

So your problem says to sum up the first n numbers of an array. Remember that indexing in an array starts at 0. So if someone wanted the sum where n=1, they would just want the first element of the array, namely new_one[0]. If n=2, the would want the sum of the first TWO elements, namely new_one[0] + new_one[1]. So in your recursion, you should say that temp = new_one[n-1], then recurse with integerSummer(new_one, n-1). That will work.

MacRumors attracts a broad audience
of both consumers and professionals interested in
the latest technologies and products. We also boast an active community focused on
purchasing decisions and technical aspects of the iPhone, iPod, iPad, and Mac platforms.