Recursion Question

I am completely lost on how to write this code in recursion. I'm supposed to write it three ways.
1. In a function that simply has a formula.
2. In a loop.
3. And in a recursive function.

I have the first two down, but I am lost on the recursive function. They are all supposed to come up with the same answer.

Any tips would be 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
#include <iostream>
#include <cmath>
#include <iomanip>
#include <cctype>
using namespace std;
int formulaEvenSum(int number);
int loopEvenSum(int loopNum);
int recursiveEvenSum(int numberTwo);
int main()
{
	int num;
	
	cout << "Enter a positive integer (or 0 to exit): " ;
	cin >> num;
	cout << endl << endl;
	
	while (num != 0)
	{
		formulaEvenSum(num);
		loopEvenSum(num);	
		cout << "Enter a positive integer (or 0 to exit): " ;
		cin >> num;
		cout << endl << endl;	
	}


 cout << endl << endl;
 system ("PAUSE");
 
 return 0;
}

int formulaEvenSum(int number)
{
	int evenSum;
	
	if(number > 0)
	{
		evenSum = (number / 2) * ((number / 2) + 1);
		cout << "Formula result = " << setw(15) << evenSum << endl;
		return evenSum;
	}
} 

int loopEvenSum(int loopNum)
{
	if(loopNum > 0)
	{
		int num = 0;
		for(int i = 2; i <= loopNum; i+= 2) num += i;
		cout << "Iterative result = " << setw(15) << num << endl;
		return num;
	}
}

int recursiveEvenSum(int numberTwo)
{
	
}
I understand how to use recursion to do simple things like count down, but I don't know how I could use it for this problem.
If you can manage a function that counts down (or up), you're pretty much there.

Your loop in loopEvenSum() counts up (in two.) And also?

Andy
Topic archived. No new replies allowed.