20-CS-122-001 Computer Science II Spring 2012
Tail Recursion: Fibonacci

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Next      Lectures      Source
#include <stdlib.h>
#include <iostream>
using namespace std;

unsigned long fib (int n, int x, int y) {
   if (n <= 1) return x;
   return fib(n-1, x+y, x);
}

int main (int argc, char **argv) {
   if (argc != 2) {
      cout << "Usage: " << argv[0] << " \n";
      exit (0);
   }
   int n = atoi(argv[1]);
   cout << "fib(" << n << ") = " << fib(n, 1, 1) << "\n";
}