need an algorithm for the Fibonacci sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
#include <iostream> using namespace std; long fib_num ( long ); int main() { long num = 0; long <strong class="highlight">sequence</strong> = 0; cout << " Enter a positive number and I will compute the <strong class="highlight">Fibonacci</strong> <strong class="highlight">sequence</strong> for that number: "; cin >> num; if ( num < 0) { cout << " Number must be greater than zero " << endl; return 1; } cout << endl << endl; <strong class="highlight">sequence</strong> = fib_num(num); cout << " The " << num << "th number of the <strong class="highlight">Fibonacci</strong> <strong class="highlight">sequence</strong> is " << <strong class="highlight">sequence</strong> << endl; return 0; } long fib_num ( long n) { if ( n == 0) { return 0; } else if ( n == 1 ) { return 1; } else return fib_num( n -1) + fib_num(n-2); }
I haven't taken that many cs classes so I just googled and got this http://www.daniweb.com/software-development/cpp/threads/28093
If you have that C book with that stupid fly surfing on the front, there is a great example of how to solve this using recursion...
Join our real-time social learning platform and learn together with your friends!