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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <iomanip>
#include <cstdlib>

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.

1
2
3
4
5
6
7
8
9
void loopEvenSum(int num, int& evenSum2)
   {
    evenSum2 = 0;
    for(int i = 1; int <= num; i++)
       {
       evenSum2 += i;
       }
   }


or what I prefer more:

1
2
3
4
5
6
7
8
9
10
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

1
2
3
4
5
6
7
void formulaEvenSum(int num, int& evenSum)
{

    evenSum = num / 2 * (num / 2 + 1);

    return;
}


I would write

1
2
3
4
5
6
7
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

1
2
3
4
5
6
7
8
9
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.