Recursive Functions: Getting the Sum of Even or Odd Integers in Given Range

I'm writing a C++ program that asks the user to enter a single number from 1 to 50 and a choice of "even" or "odd". Using a recursive function, it will then output the sum of all the even or odd integers from 1 up to (and including) that number.

For example, if 6 and "even" are specified, the function will return the value: 2 + 4 + 6 = 12. If 6 and "odd" are specified, the function will return the value 1 + 3 + 5 = 9.

I already got the rest figured out, but the only thing I'm stuck on is how to get the sum of all the even or odd integers from 1 up to (the inputted integer). If anyone could give me hints on how to do this, I would appreciate it.

My Code:
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
#include <iostream>
using namespace std;

int sumAll(int, string);

int main()
{
    int num;
    string evenOrOdd;

    cout << "Enter a number from 1 to 50: ";
    cin >> num;
    //...prompt for even or odd then call
    // sumAll().

    cout << "Even or odd?: ";
    cin >> evenOrOdd;

    sumAll(num, evenOrOdd);
    return 0;

}
    // Recursive function to compute the sum
    // of even or odd numbers up to 'n'.
    int sumAll(int n, string i)
    {
        
        cout << "The sum of the " << i << " numbers from 1 to "
             << n << " is: " << sumAll << endl;
    }


My Output:
1
2
3
Enter a number from 1 to 50: 10
Even or odd?: even
The sum of the even numbers from 1 to 10 is: 1


Expected Output:
1
2
3
Enter a number from 1 to 50: 10
Even or odd?: even
The sum of the even numbers from 1 to 10 is: 30

Last edited on
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
#include <iostream>
#include <cctype>   // for toupper

int addNumbers(int);

int main()
{
   std::cout << "Enter a number from 1 to 50: ";
   int num;
   std::cin >> num;

   std::cout << "[E]ven or [O]dd? (single character): ";
   char evenOrOdd;
   std::cin >> evenOrOdd;
   std::cout << '\n';

   // convert the char to upper case
   evenOrOdd = ::toupper(evenOrOdd);

   // if odd is chosen and the starting number is even, or
   // if even is chosen and the starting number is odd subtract 1
   if ((evenOrOdd == 'O' && num % 2 == 0) || (evenOrOdd == 'E' && num % 2 == 1))
   {
      num--;
   }

   int sum = addNumbers(num);

   std::cout << "The sum is " << sum << '\n';
}

int addNumbers(int n)
{
   // create a variable that persists between function calls
   static int sum = 0;

   // if the end of the series has been reached, return the total sum
   if (n <= 0)
   {
      return sum;
   }

   // add the current number to the sum
   sum += n;

   return addNumbers(n - 2);
}
Enter a number from 1 to 50: 10
[E]ven or [O]dd? (single character): e

The sum is 30


Recursion makes this much more complicated than it needs to be. Non-recursive function (the rest of main is the same):
32
33
34
35
36
37
38
39
40
41
42
int addNumbers(int n)
{
   int sum = 0;

   for (int loop = n; loop > 0; loop -= 2)
   {
      sum += loop;
   }

   return sum;
}
Last edited on
There are a couple of ways to do this with std::string instead of char (remember to #include <string> ):

1:
12
13
14
15
16
17
18
19
   std::cout << "[E]ven or [O]dd? ";
   std::string evenOrOdd;
   std::cin >> evenOrOdd;
   std::cout << '\n';

   // if odd is chosen and the starting number is even, or
   // if even is chosen and the starting number is odd subtract 1
   if ((::tolower(evenOrOdd[0]) == 'o' && num % 2 == 0) || (::tolower(evenOrOdd[0]) == 'e' && num % 2 == 1))


2 (#include <algorithm> ):
13
14
15
16
17
18
19
20
21
22
23
std::cout << "[E]ven or [O]dd? ";
   std::string evenOrOdd;
   std::cin >> evenOrOdd;
   std::cout << '\n';

   // http://www.cplusplus.com/reference/algorithm/transform/
   std::transform(evenOrOdd.begin(), evenOrOdd.end(), evenOrOdd.begin(), ::tolower);

   // if odd is chosen and the starting number is even, or
   // if even is chosen and the starting number is odd subtract 1
   if ((evenOrOdd == "odd" && num % 2 == 0) || (evenOrOdd == "even" && num % 2 == 1))


One of the problems with using a string for evaluating input is if you don't transform the entire string to either upper or lower case an exact match is hard to make. "Odd" is not "ODD" or "odd".

Plus the user has to enter the correct word. "efen" is not "even", etc.

Evaluating a string is doable, but it requires more work on your part than using a char for input.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;

int main()
{
   int num;
   string parity;
   cout << "Enter a positive number: ";   cin >> num;
   cout << "even or odd?: ";   cin >> parity;
   
   if      ( parity == "even" ) cout << "Sum is " << ( num / 2 ) * ( num / 2 + 1 ) << '\n';
   else if ( parity == "odd"  ) cout << "Sum is " << ( ( num + 1 ) / 2 ) * ( ( num + 1 ) / 2 ) << '\n';
   else                         cout << "Invalid parity\n";
}


If you absolutely HAVE to do it by recursion:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
using namespace std;

int sumAlt( int n ) { return n < 2 ? n : n + sumAlt( n - 2 ); }

int main()
{
   int num = 0;
   while( num <= 0 )
   {
      cout << "Enter a positive number: ";   cin >> num;
   }

   string parity = "";
   while( parity != "even" && parity != "odd" )
   {
      cout << "even or odd?: ";   cin >> parity;
   }

   string numParity = num % 2 ? "odd" : "even";
   cout << "Sum is " << sumAlt( num - ( parity != numParity ) ) << '\n';
}
Last edited on
Topic archived. No new replies allowed.