// --------------------------------------- // recurse.cpp record recursion depth // --------------------------------------- #include "w.h" long fact(int n, int &d) // d counts calls to fact { if (n == 1) return 1; else { d++; return n*fact(n-1,d); }} long fib(int n, int &d) // calls to fib { if ((n ==1)||(n == 2)) return 1; else { d++; return fib(n-2,d)+fib(n-1,d); }} //---------------------------------------------------- void main() { int k,d; nl(0); banner("recurse.cpp"); k = 9; d = 0; p("fact(");p(k); pl(") = ",fact(k,d)); pl("recursion depth = ",d); nl(); // default int arithmetic 'stops' at 2^15-1 p("1*2*3*4*5*6*7*8*9 = "); cout << 1*2*3*4*5*6*7*8*9; nl(); long g = 1; // store the result in long for (int i = 2; i < 10; i++) g = g*i; pl(g); nl(); k = 20; d = 0; p("fib(");p(k); pl(") = ",fib(k,d)); pl("calls to fib = ",d); } /* output ------------- recurse.cpp ------------- fact(9) = 362880 recursion depth = 8 1*2*3*4*5*6*7*8*9 = -30336 362880 fib(20) = 6765 calls to fib = 6764 */ /* ------------------------------------------------ Note The Tower of Hanoi This famous puzzle is solved by one recursive function. Can you fill in the details? void hanoi::movetower(int j, int a, int b) { if (j > 0) { movetower(j-1, a, otherpeg(a,b)); movedisc(j,a,b); movetower(j-1,otherpeg(a,b),b); } } --------------------------------------------------*/