Home Segments Index Top Previous Next

351: Mainline

Capturing the rabbit formula in the form of a C++ function, you have the following:

#include  
// Define rabbits function: 
int rabbits (int n) { 
  if (n == 0 || n == 1) 
    return 1; 
  else return rabbits (n - 1) + rabbits (n - 2); 
} 
// Test rabbits function: 
main ( ) { 
  cout << "At the end of month 1, there is "  << rabbits (1) << endl 
       << "At the end of month 2, there are " << rabbits (2) << endl 
       << "At the end of month 3, there are " << rabbits (3) << endl 
       << "At the end of month 4, there are " << rabbits (4) << endl 
       << "At the end of month 5, there are " << rabbits (5) << endl; 
} 
--- Result --- 
At the end of month 1, there is 1 
At the end of month 2, there are 2 
At the end of month 3, there are 3 
At the end of month 4, there are 5 
At the end of month 5, there are 8