bsc

Comprehensive codebase and coursework for the 4-year B.Sc. Computer Science Honours degree (WBSU)

git clone https://github.com/notamitgamer/bsc.git
· rebuilt hourlyOpen on GitHub
root / semester_2 / assignments / assignment_15.cpp

assignment_15.cpp (1615B)


      1 /* WAP to display Fibonacci series (i) using recursion, (ii) using iteration. */
      2 
      3 #include <iostream>
      4 using namespace std;
      5 
      6 class Fibonacci {
      7 private:
      8     int n;
      9 
     10     int fibRecursive(int k) {
     11         if (k <= 0) return 0;
     12         if (k == 1) return 1;
     13         return fibRecursive(k - 1) + fibRecursive(k - 2);
     14     }
     15 
     16 public:
     17     Fibonacci(int count) { n = count; }
     18 
     19     void displayRecursive() {
     20         cout << "Fibonacci (Recursive): ";
     21         for (int i = 0; i < n; i++) cout << fibRecursive(i) << " ";
     22         cout << endl;
     23     }
     24 
     25     void displayIterative() {
     26         cout << "Fibonacci (Iterative): ";
     27         if (n <= 0) { cout << endl; return; }
     28         int first = 0, second = 1;
     29         for (int i = 0; i < n; i++) {
     30             if (i == 0) cout << first << " ";
     31             else if (i == 1) cout << second << " ";
     32             else {
     33                 int nextTerm = first + second;
     34                 cout << nextTerm << " ";
     35                 first = second;
     36                 second = nextTerm;
     37             }
     38         }
     39         cout << endl;
     40     }
     41 };
     42 
     43 int main() {
     44     int n, choice;
     45     cout << "Enter number of terms: ";
     46     cin >> n;
     47     if (n < 0) { cout << "Invalid number of terms!\n"; return 0; }
     48 
     49     Fibonacci fib(n);
     50     while (true) {
     51         cout << "1.Recursive 2.Iterative -1.Exit\n";
     52         cout << "Enter your choice: ";
     53         cin >> choice;
     54 
     55         switch (choice) {
     56             case 1: fib.displayRecursive(); break;
     57             case 2: fib.displayIterative(); break;
     58             case -1: cout << "Exiting...\n"; return 0;
     59             default: cout << "Wrong choice.\n";
     60         }
     61     }
     62 }