Recursive to iteration

Hi, I need some help on this. I need to convert the recursive version to iteration version using while loop but I just cant get it right. There is something wrong with my iteration version..Thanks you alot!

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

int recusion(int);
int iteration(int);


int main ()
{
	int n;

	cout << "Enter a integers: ";
	cin >> n;

	cout << recusion(n);
	cout << endl;
	cout << iteration(n);
	cout << endl;
	
}

int recusion(int n)
{
	if(n == 1)
		return 3;
	else if(n == 2)
		return 2;
	else			
		return recusion(n - 2) + recusion(n - 1);
}

int iteration(int n)
{
	int pCur = 0;
	int pNext = 0;
	int pOld = 0;
	int i = 1;
	
	while(i <= n)
	{
		if(i == 1)
		{
			pNext += 3;
			pCur = 3;
			if (n == 1)
				return pCur;
		}
		else if(i == 2)
		{
			pNext += 2; 
			pCur = 2;
			if (n == 2)
				return pCur;
		}	 
		else
			pNext = pCur + pOld;
		
		pOld = pCur;
		pCur = pNext; 
		
		i++;
	}
	return pNext;
}
Last edited on
[code]Your code goes here.[/code]
In the iterative version you are calculating one number ahead, so the loop should end early. You may want to change the handling of the special cases.
Topic archived. No new replies allowed.