Write a C++ program using the concept of OOP to print the Fibonacci series unto n terms.
Algorithm:
- Create a Fibonacci class with private variable n to store the number of terms of the Fibonacci series to be printed.
- 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.
- In the main() function, prompt the user to enter a number.
- Create a Fibonacci object with the number entered by the user.
- Call the print() method of the Fibonacci object to print the Fibonacci series of the first n terms.
- 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