L-17 MCS 275 Fri 16 Feb 2001

Below are the listings for the programs we discussed in class.
/* L-17 MCS 275 Fri 16 Feb 2001 : recursive and iterative Fibonacci */

#include <stdio.h>

int rec_Fib (int n, int* k);
/* recursive computation of the n-th Fibonacci number,
   which is returned by this function;  the k on return
   contains the number of function calls */
int itr_Fib (int n);
/* iterative computation of the n-th Fibonacci number */

int main()
{
   int n,fn,cnt;

   printf("Computing Fibonacci numbers recursively and iteratively.\n");
   printf("  Give a natural number : "); scanf("%d", &n);
   printf("Recursive calculation...\n");
   cnt = 0;
   fn = rec_Fib(n,&cnt);
   printf("  Fibonacci number %d is %d.\n", n, fn);
   printf("  This took %d function calls.\n", cnt);
   printf("Iterative calculation...\n");
   fn = itr_Fib(n);
   printf("  Fibonacci number %d is %d.\n", n, fn);

   return 0;
}

int rec_Fib (int n, int* k)
{
   int sum,left,right;

   if ((n == 0) || (n == 1))
   {
      *k = 0;
      return 1;
   }
   else
   {
      sum = rec_Fib(n-1,&left) + rec_Fib(n-2,&right);
      *k = 2 + left + right;
      return sum;
   }
}

int itr_Fib (int n)
{
   int i,first,second,sum;

   if ((n == 0) || (n == 1))
      return 1;
   else
   {
      first = 1;
      second = 1;
      for (i = 2; i <= n; i++)
      {
         sum = first + second;
         first = second;
         second = sum;
      }
      return sum;
   }
}