for n is 0 int factorial int n if n 0 return 1 else return n factorial n 1 int

For n is 0 int factorial int n if n 0 return 1 else

This preview shows page 2 - 4 out of 4 pages.

/* iterative solutions computes n! for n is >=0 */ int factorial (int n) {   if (n == 0)     return 1; else      return( n * factorial (n-1));  } int factorial (int n) { int i, product=1; for (i=n; i>1; --i)  /*     n * (n-1) * (n-2)…*1   */  product=product *i;   return (product); }  
Image of page 2
                    base* base  exp-1       for exp>0 (General Recursive case). Implementation of Power Function: Recursive Iterative int power(int base, int exp) {  if ( exp = = 0)   return (1); else  return (base * power(base, exp –1)); }   int power_it(int base, int exp) int count, product; product=1; for ( count = exp; count >0; count --) product = product * base; return ( product); }      OR   int power(int base, int exp) { int p=1; while(exp !=0) { p *= base; exp --; return p; }   Example #3: Fibonacci Sequence: The Fibonacci numbers are a sequence of numbers that have many varied uses  the Fibonacci sequence          0, 1, 1,2,3,5,8,13,21,34   Fibonacci number Begins with the term 0 and 1 and has the property that each succeeding term is  the sum of the two preceeding terms.   Fibonacci(0) is 0  Fibonacci (1) is 1    Fibonacci( n)= Fibonacci (n-2) + Fibonacci (n-1)  , for n >=2    This is defined recursively as:   Page 3 of 4
Image of page 3
f = 0, f = 1 f i  = f i-2  + f i-1   for i=2,3, ..
Image of page 4

You've reached the end of your free preview.

Want to read all 4 pages?

  • Spring '10
  • zaman
  • Recursion, Control flow, base case, Recursive int power

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

Stuck? We have tutors online 24/7 who can help you get unstuck.
A+ icon
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes