Adding an extra 2

Can someone explain why I am getting an extra 2 added to my sum PLEASE!!!

1
2
3
4
5
6
int LoopEvenSum (int num, int &finalLoopSum)
{
     //will compute and return the same sum using iteration (i.e. a loop).
     for (int i = 0; i <= num; i += 2)
     finalLoopSum += i;
}


For a better understanding, the program should be calculating the sum of all EVEN integers from 1 to num (inclusive). Therefore, if num = 5, finalLoopSum should = 6 because (2+4 = 6). If num = 10, finalLoopSum should = 30 because (2+4+6+8+10 = 30). However, I am getting 8 instead of 6, and 32 instead of 30, thus the extra 2. All help is greatly appreciated, as always!
Maybe you forgot to set an initial velue for finalLoopSum.

1
2
3
4
5
6
7
int LoopEvenSum (int num, int &finalLoopSum)
{
     //will compute and return the same sum using iteration (i.e. a loop).
     finalLoopSum = 0;
     for (int i = 0; i <= num; i += 2)
     finalLoopSum += i;
}
Last edited on
My greatest appreciation. Works beautifully now! What a fresh set of eyes will do :)
Any ideas on how to find the same calculation using recursion??
Also you return nothing from the function. I would declare it as

1
2
3
4
5
6
7
8
9
int LoopEvenSum( int num )
{
     //will compute and return the same sum using iteration (i.e. a loop).
     int sum = 0;

     for (int i = 0; i <= num; i += 2) sum += i;

     return ( sum );
}


and in the main

finalLoopSum = LoopEvenSum( num );

Last edited on
Yeah, I had that, I just didn't show ALL of the code, there is much more to the program than that little piece and didn't want to include a ton of info when I knew the issue was somewhere in that small piece :)
For example the following way


1
2
3
4
int LoopEvenSum ( int num )
{
    return ( ( num > 1 ) ? 2 + LoopEvenSum ( num - 2 ) : 0 );
}


and in the main

1
2
3
std::cout << LoopEvenSum( 6 ) << std::endl;
std::cout << LoopEvenSum( 7 ) << std::endl;
std::cout << LoopEvenSum( 8 ) << std::endl;
Last edited on
I have no idea what that means...this is my first time hearing about recursion, and Im not quite sure im grasping it
Recursion is when a function calls itself that to get a final result. Look

1
2
3
4
int LoopEvenSum ( int num )
{
    return ( ( num > 1 ) ? 2 + LoopEvenSum ( num - 2 ) : 0 );
}


for example for num = 5 you call

LoopEvenSum( 5 );

Inside the function as 5 > 1 there is another call of it

2 + LoopEvenSum( 3 );

then in turn the next call calls the same function

( 2 + LoopEvenSum( 3 ) ) + ( 2 + LoopEvenSum( 1 ) );
At last when we have LoopEvenSum( 1 ) it returns 0. So we will get

1
2
3
4
5
( 2 + LoopEvenSum( 3 ) )
             |
              -> + ( 2 + LoopEvenSum( 1 ) ) 
                                   |
                                   -> + ( 0 );

and as the result 4



Last edited on
Interesting...
this was the only real example I was given in my course and it's rather confusing

1
2
3
4
5
6
7
<return value> func1 (<parameter list>) 
{
  if (<condition>)
      <base case>
  else
      <recursive case>
}
In you example applied to the function I showed the base condition is

num < 2 and in this case the function return 0.

and recursion is calling the function itself with the value that 2 less than the previous value of num and adding 2 to its result.
It's not really that confusing. It's also the way your PC's Search File Functionality works.

Like...

1
2
3
4
5
6
7
8
9
// WARNING!! PSEUDOCODE OVER!!
void ScanFolders()
{
    while(ThereIsAnotherFolderInThisFolder())
    {
        GetNewFolderName();
        ScanFolders();
    }
}


So, for each folder, if there is another folder, it's gonna search into the folder you just found.

I hope this cleared some ideas a bit.
It makes a little more sense now, I'm still reading up on it...hopefully i get a decent understanding of it. This is my entire program so far, only 2 issues I have left
number 1 - program should loop until user exits with the number 0, however, in doing so...say for the first num i enter 10..and my answers should all be 30...then looping through i enter 5 for the num and my answers should all be 6, tho my answer for the iterative loop is 36. It is not emptying the bank, rather it is holding its previous value. I thought by setting it to 0, would correct that. Any thoughts?
number 2 - the recursive function, is way off in value. Where my answer should be 30, it is 2293570 (i am working on debugging that right now, but of course thoughts and suggestions are appreciated)

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

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

// function prototypes
int FormulaEvenSum (int num, int &finalFormulaSum);
int LoopEvenSum (int num, int &finalLoopSum);
int RecursiveEvenSum (int num, int &finalRecursiveSum);

int main()
{
    int num;
    int finalFormulaSum = 0;
    int finalLoopSum = 0;
    int finalRecursiveSum = 0;
    
    cout << "Program to compute sum of even integers from 1 to num" << endl << endl; 

    // Read a positive integer from the user (indicating that if the user enters 0, the program will exit)    
    // Error check the number entered, and loop until the user enters a positive integer
    do
    {
        cout << "Enter a positive integer (or 0 to exit): ";
        cin >> num;
        
        cout << endl;
        
        // The program should loop and continue to compute results for new values of num, until the user enters 0 for the value of num.   
        if (num != 0)
        {
            FormulaEvenSum (num, finalFormulaSum);                                // funciton call
        
            LoopEvenSum (num, finalLoopSum);                                      // function call
        
            RecursiveEvenSum (num, finalRecursiveSum);                            // function call

            cout << "Formula result = " << finalFormulaSum << endl;
            cout << "Iterative result = " << finalLoopSum << endl;
            cout << "Recursive result = " << finalRecursiveSum << endl << endl;
        }
        
        // invalid entry
        if (num < 0)
        {
            cout << "Invalid Entry! Please try again!" << endl;
        }
    }
    while (num != 0);
    
    if (num == 0)
    { 
        // exit the program
        cout << "Goodbye!" << endl << endl;
    }
    
    system("PAUSE");
}

int FormulaEvenSum (int num, int &finalFormulaSum)
{     
    // formula to compute the sume of the even integers       
    finalFormulaSum = ((num/2) * ((num/2) + 1));
}

int LoopEvenSum (int num, int &finalLoopSum)
{
    // will compute and return the same sum using iteration
    for (int i = 0; i <= num; i += 2)
    finalLoopSum += i;
}

int RecursiveEvenSum (int num, int &finalRecursiveSum)
{
    // will compute and return the same sum using recursion.
    if (num < 2)
    {
        finalRecursiveSum = 0;
    }
    
    else
    {
        finalRecursiveSum = 2 + RecursiveEvenSum (num - 2, finalRecursiveSum);
    }
}
I have updated this function. It looks now as

the declaration

void RecursiveEvenSum (int num, int &finalRecursiveSum);

and the definition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void RecursiveEvenSum (int num, int &finalRecursiveSum)
{
    // will compute and return the same sum using recursion.
    if (num < 2)
    {
        finalRecursiveSum = 0;
    }
    
    else
    {
        RecursiveEvenSum (num - 2, finalRecursiveSum);
        finalRecursiveSum += 2 * ( num / 2 ) ; 
    }
}
Last edited on
This one shall be defined as


1
2
3
4
5
6
7
8
9
int LoopEvenSum ( int num )
{
    // will compute and return the same sum using iteration
    sum = 0;

    for (int i = 0; i <= num; i += 2) sum += i;

    return ( sum );
}

I have updated the recursive function one more because it had an incorrect expression.
Last edited on
As for LoopEvenSum function, If I remove the output parameter and declare sum locally, then I cannot use that sum in main...and I am not allowed to use global variables.
I have not understood. In the main you write


finalLoopSum = LoopEvenSum( num );

Or define it the following way

1
2
3
4
5
6
7
void LoopEvenSum ( int num, int &finalLoopSum )
{
    // will compute and return the same sum using iteration
    finalLoopSum = 0;

    for (int i = 0; i <= num; i += 2) finalLoopSum += i;
}
I found the issue. I can't actually declare a variable that i am also using as an input/output parameter. I was passing it as an output parameter, and also declaring within that function that int finalLoopSum = 0, rather than disregarding "int". Now that i removed the "int", program works fine.
Aside from the recursive function of course. That one is still a little wacky.
Also, would I be wrong in using int rather than void? I noticed you are using void, where I am using int. Why?
Topic archived. No new replies allowed.