understaning recurssion and unwrapping

I would like to understand exactly how the fibonacci sequence is obtained, given that a recursive c++ function unwraps itself for each iteration.
for example the following recursive function:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
void countdown(int n) {
  std::cout << n << ": Count  .. (n at " << &n << ")"<< std::endl;
  if (n > 0)
    countdown(n-1);
  std::cout << n << ": Unwrap .. (n at " << &n << ")" << std::endl;
}

int main() {
  countdown(4);
  return 0;
}

the out put is
1
2
3
4
5
6
7
8
9
10
4: Count  .. (n at 0x7ffd086826ec)
3: Count  .. (n at 0x7ffd086826cc)
2: Count  .. (n at 0x7ffd086826ac)
1: Count  .. (n at 0x7ffd0868268c)
0: Count  .. (n at 0x7ffd0868266c)
0: Unwrap .. (n at 0x7ffd0868266c)
1: Unwrap .. (n at 0x7ffd0868268c)
2: Unwrap .. (n at 0x7ffd086826ac)
3: Unwrap .. (n at 0x7ffd086826cc)
4: Unwrap .. (n at 0x7ffd086826ec)
the Unwrap is called for each original call.
So given the above, what occurs when the below fibonacci function unwraps?
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>
using namespace std;

int fib(int n)
{
	if(n<=0) return 0;
	else if(n==1) return 1;
	else return fib(n-1) + fib(n-2);
}

int main() {		
	int seed = 0;
	cout << "Seed = ";
	cin >> seed;

	cout << endl << "Recursive function results" << endl;
	for(int i = 1; i <= seed; ++i)
    cout << "For i = " << i << "  result is " << fib(i) << endl;

	cout << endl;

  return 0;
}
Last edited on
Topic archived. No new replies allowed.