Source of iterativeRabbit.cpp


  1: //  Created by Frank M. Carrano and Timothy M. Henry.
  2: //  Copyright (c) 2017 Pearson Education, Hoboken, New Jersey.

  4: /** Iterative solution to the rabbit problem. */
  5: int iterativeRabbit(int n)
  6: {
  7:    // Initialize base cases:
  8:    int previous = 1; // Initially rabbit(1)
  9:    int current = 1;  // Initially rabbit(2)
 10:    int next = 1;     // Result when n is 1 or 2
 11:    
 12:    // Compute next rabbit values when n >= 3
 13:    for (int i = 3; i <= n; i++)
 14:    {
 15:       // current is rabbit(i - 1), previous is rabbit(i - 2)
 16:       next = current + previous;   // rabbit(i)
 17:       previous = current;          // Get ready for next iteration
 18:       current = next;
 19:    }  // end for
 20:    
 21:    return next;
 22: }  // end iterativeRabbit