1: /** @file fibonacci_iterative.cpp 2: Outputs the first n Fibonacci numbers. 3: */ 5: #include <iostream> 6: #include <iomanip> 7: #include <string> 8: using namespace std; 10: int fibonacci 11: ( 12: int n //in 13: ) 14: /**< 15: Compute and the nth Fibonacci number, i.e. the nth term of 16: the sequence 1, 1, 2, 3, 5, 8, 13, ... 17: @return The nth Fibonacci number. 18: @pre n contains a positive integer. 19: @post No other side effects. 20: */ 21: { 22: if (n == 1 || n == 2) return 1; 23: 24: int secondLast = 1; 25: int last = 1; 26: int result = 0; 27: 28: for (int i=3; i<=n; i++) 29: { 30: result = last + secondLast; 31: secondLast = last; 32: last = result; 33: } 34: return result; 35: } 38: void main(void) 39: { 40: cout << "\nThis program outputs the first n " 41: "Fibonacci numbers (n entered by the user).\n"; 42: string response; 43: do 44: { 45: int n; 46: cout << "Enter the number of terms you want: "; 47: cin >> n; cin.ignore(80, '\n'); 48: cout << "Here are the first " << n << " Fibonacci numbers:\n\n"; 49: int count = 0; 50: for (int i = 1; i <= n; i++) 51: { 52: cout << setw(10) << fibonacci(i); 53: count++; 54: //if (count%8 == 0) cout << "\n"; 55: //Above line not necessary on Windows, since if 80 characters 56: //on a line is reached, an automatic newline is inserted. 57: } 58: if (count%8 != 0) cout << "\n\n"; else cout << "\n"; 59: //The else part is needed in the above line to produce the blank 60: //line after the table in the case when the total number of values 61: //is a multiple of 8. 62: cout << "Just press Enter to do it again, anything else to quit: "; 63: getline(cin, response); 64: } 65: while (response == ""); 66: }