Recursive Sum of Odd Numbers

Returns the sum of odd numbers from an array

Page 1 of 1

3 Replies - 7369 Views - Last Post: 07 March 2010 - 09:36 PM Rate Topic: -----

#1 marcelomg  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • 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;
}

Was This Post Helpful? 0
  • +
  • -

#3 marcelomg  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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)
Was This Post Helpful? 0
  • +
  • -

#4 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • 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...
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1