Source of fibonacci.cpp


  1: /** @file fibonacci.cpp
  2: Outputs the first n Fibonacci numbers.
  3: */

  5: #include <iostream>
  6: #include <iomanip>
  7: using namespace std;

  9: #include "utilities.h"
 10: using Scobey::Pause;
 11: using Scobey::ReadInt;
 12: using Scobey::userSaysYes;


 15: int fibonacci
 16: (
 17:     int n //in
 18: )
 19: /**<
 20: Compute and the nth Fibonacci number, i.e. the nth term of
 21: the sequence 1, 1, 2, 3, 5, 8, 13, ...
 22: @return The nth Fibonacci number.
 23: @pre n contains a positive integer.
 24: @post No other side effects.
 25: */
 26: {
 27:     if (n == 1  ||  n == 2)
 28:         return 1;
 29:     else
 30:         return fibonacci(n-2) + fibonacci(n-1);
 31: }


 34: void main(void)
 35: {
 36:     cout << "\nThis program outputs the first n "
 37:             "Fibonacci numbers (n entered by the user).\n";
 38:     Pause();

 40:     do
 41:     {
 42:         int n;
 43:         ReadInt("Enter the number of terms you want: ", n);
 44:         cout << "Here are the first " << n << " Fibonacci numbers:\n\n";
 45:         int count = 0;
 46:         for (int i = 1; i <= n; i++)
 47:         {
 48:             cout << setw(10) << fibonacci(i);
 49:             count++;
 50:             //if (count%8 == 0) cout << "\n";
 51:             //Above line not necessary on Windows, since if 80 characters
 52:             //on a line is reached, an automatic newline is inserted.
 53:         }
 54:         if (count%8 != 0) cout << "\n\n"; else cout << "\n";
 55:         //The else part is needed in the above line to produce the blank
 56:         //line after the table in the case when the total number of values
 57:         //is a multiple of 8.
 58:     }
 59:     while (userSaysYes("Do it again?"));
 60: }