# Recursive Sum of Odd Numbers

Page 1 of 1

## 3 Replies - 14720 Views - Last Post: 07 March 2010 - 09:36 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=160463&amp;s=7f75f82ccf1e56f68738ec372794e8b0&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 marcelomg

• New D.I.C Head

Reputation: 0
• Posts: 21
• Joined: 10-January 09

# Recursive Sum of Odd Numbers

Posted 07 March 2010 - 06:19 PM

Hello,

I'm trying to write a recursive function that returns the sum of odd numbers from an array.
It's not really working but I can't figure out why.
Any help would be appreciated,

thanks,

```#include <iostream>
using namespace std;

const int MAX = 10;
int a[ MAX ] = {1,2,3,4,5,6,7,8,9,10};

int smallResult = 0;

int sumOdd( int MAX[], int n )
{
if ( n == 0 )
return 0;
else{
int smallResult = sumOdd( MAX + 1, n - 1 );
return smallResult + MAX[ 0 ];
}

}
int main ()
{
cout << "Sum of Odd is: " << smallResult << endl;
}
```

This post has been edited by marcelomg: 07 March 2010 - 06:53 PM

Is This A Good Question/Topic? 0

## Replies To: Recursive Sum of Odd Numbers

### #2 NickDMax

• Can grep dead trees!

Reputation: 2255
• Posts: 9,245
• Joined: 18-February 07

## Re: Recursive Sum of Odd Numbers

Posted 07 March 2010 - 07:33 PM

Here is an example:
```#include <iostream>

int sum(int *begin, int *end) {
std::cout << *begin << std::endl;
if(begin == end)  { return *begin; }
return *begin + sum(begin + 1, end);
}

int main() {
int array[] = { 1, 3, 14, 54, 23, 84, 12, 2, 43, 1 };
int size = sizeof(array)/sizeof(int);
std::cout << "sum is: " << sum(array, array + size - 1) << std::endl;
return 0;
}
```

### #3 marcelomg

• New D.I.C Head

Reputation: 0
• Posts: 21
• Joined: 10-January 09

## Re: Recursive Sum of Odd Numbers

Posted 07 March 2010 - 09:29 PM

thanks for your reply but your function is returning the sum of all numbers. I need just the ODD numbers.

{ 1, 3, 14, 54, 23, 84, 12, 2, 43, 1 } in this case: (1,3,23,43,1)

### #4 NickDMax

• Can grep dead trees!

Reputation: 2255
• Posts: 9,245
• Joined: 18-February 07

## Re: Recursive Sum of Odd Numbers

Posted 07 March 2010 - 09:36 PM

well I was not going to DO it for you... all you have to do though is add a little logic to only add in the odd values...