Write a C++ program using the concept of OOP to print the Fibonacci series unto n terms


Write a C++ program using the concept of OOP to print the Fibonacci series unto n terms. 

Algorithm:

  1. Create a Fibonacci class with private variable n to store the number of terms of the Fibonacci series to be printed.
  2. Define a public method print() in the class to calculate and print the Fibonacci series of the first n terms by using a loop and the Fibonacci formula c = a + b, where a and b are the previous two terms and c is the current term.
  3. In the main() function, prompt the user to enter a number.
  4. Create a Fibonacci object with the number entered by the user.
  5. Call the print() method of the Fibonacci object to print the Fibonacci series of the first n terms.
  6. End the program.


Coding: 

#include <iostream>

using namespace std;
 
class Fibonacci {
  private:
    int n;
  public:
    Fibonacci(int x) {
      n = x;
    }
 
    void print() {
      int a = 0, b = 1, c;
      cout << a << " " << b << " ";
      for (int i = 2; i < n; i++) {
        c = a + b;
        cout << c << " ";
        a = b;
        b = c;
      }
    }
};
 
int main() {
  int num;
 
  cout << "Enter number of Fibonacci series terms to print: ";
  cin >> num;
 
  Fibonacci f(num);
 
  f.print();
 
  return 0;
}
 
/* 
Input:
Enter number of Fibonacci series terms to print: 10
 
Output:
0 1 1 2 3 5 8 13 21 34
*/

#OOP
#HappyProgramming
#HappyCoding

No comments:

Post a Comment