20-CS-122-001 Computer Science II Spring 2012
Recursion: Factorial, Tail Recursion W/ Static Accumulator

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

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

unsigned long factorial (int n) {
   static unsigned long acc = 1;
   if (n <= 0) return acc;
   acc *= n;
   return factorial (n-1);
}

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