### Function to compute sum of all even integers from 1 to num (inclusive)

I'm having a bit of a hard time creating a function, using iteration, to find the sum of all even integers between 1 and the number the user inputs. The program guidelines require a function to solve this three ways; a formula, iteration, and recursion. This is what I have so far.
 ``1234567891011121314151617181920212223242526272829303132333435363738394041`` ``````#include #include #include using namespace std; void formulaEvenSum(int num, int& evenSum) { evenSum = num / 2 * (num / 2 + 1); return; } void loopEvenSum(int num, int& evenSum2) { } int main() { int num, evenSum, evenSum2; cout << "Program to compute sum of even integers from 1 to num."; cout << endl << endl; cout << "Enter a positive integer (or 0 to exit): "; cin >> num; formulaEvenSum(num, evenSum); loopEvenSum(num, evenSum2); cout << "Formula result = " << evenSum << endl; cout << "Iterative result = " << evenSum2 << endl; system("PAUSE"); return 0; }``````

Any and all help would be appreciated. :]
Last edited on
To do this by reference like you are attempting to do.

 ``123456789`` ``````void loopEvenSum(int num, int& evenSum2) { evenSum2 = 0; for(int i = 1; int <= num; i++) { evenSum2 += i; } } ``````

or what I prefer more:

 ``12345678910`` ``````int loopEvenSum(int num) { int sum = 0; for(int i = 1; int <= num; i++) { sum =+ i; } return sum; } ``````

I prefer the latter but both should work!
Last edited on
Thanks. :)

I need to have it pass via reference, so I went with the first one. I"m at work, and am using compilr.com, but the function isn't working?

Could you give a recursive example too?
Last edited on
closed account (3qX21hU5)
never trust online compilers is my experiance usually they get it wrong.
It is a bad idea to declare a function such a way when the function has return type void and at the same time has one "output" parameter. It is better to declare it returning a value. So instead of

 ``1234567`` ``````void formulaEvenSum(int num, int& evenSum) { evenSum = num / 2 * (num / 2 + 1); return; }``````

I would write

 ``1234567`` ``````unsigned int formulaEvenSum( unsigned int num ) { unsigned int evenSum = num / 2 * (num / 2 + 1); return ( evenSum ); }``````

Take into account that your original function does not work correctly if an argument is negative. So it is better to declare it having a parameter of type unsigned int.

As for the second function then it is very simple

 ``123456789`` ``````unsigned int loopEvenSum( unsigned int num ) { unsigned int evenSum = 0; for ( unsigned int i = 2; i <= num; i += 2 ) evenSum += i; return ( evenSum ); }``````

Last edited on
Topic archived. No new replies allowed.