0

Hello,
I'm stuck with this code and I can't figure out how to make it work. I need to get the Sum of Odd numbers from an array. For some reason it returns 0.
I'm new to programming, so any help would be appreciated, thanks.
Here it is:

#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;
	return 0;
}
4
Contributors
3
Replies
5
Views
7 Years
Discussion Span
Last Post by syd919
0

Why is that a recursive function ??? A simple loop with the mod operator % (to find out whether the number is even or odd) will do the trick. No point in overcomplicating that function unless recursion is required by your teacher.

0

You are expecting smallResult to be populated by the sumOdd function without calling the function.

For the code in sumOdd to be executed , you need to call the sumOdd function from the main function.

0

ancient dragon is right ,with the use of the "%" operator you need less lines for your code, recursion mostly is more complicated than using a loop.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.