Advertisement
skb50bd

Fibonacci (Iterative and Recursive)

Mar 29th, 2016
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.53 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int recursiveFib(int n) {
  5.     if (n <= 1) return n;
  6.     else return recursiveFib(n - 1) + recursiveFib(n - 2);
  7. }
  8.  
  9. int iterativeFib(int n) {
  10.     int f1 = 0;
  11.     int f2 = 1;
  12.     int temp;
  13.     for (int i = 0; i < n; i++) {
  14.         temp = f1;
  15.         f1 = f2;
  16.         f2 += temp;
  17.     }
  18.     return f1;
  19. }
  20.  
  21. int main() {
  22.     int n;
  23.  
  24.     cin >> n;
  25.  
  26.     cout << "Recursive Fib: " << recursiveFib(n) << endl;
  27.     cout << "Iteraive Fib: " << iterativeFib(n) << endl;
  28.  
  29.     return 0;
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement