# C++ Program to print Fibonacci Series using Class template

Given a number n, the task is to write a program in C++ to print the n-terms of Fibonacci Series using a Class template

The Fibonacci numbers are the numbers in the following integer sequence.

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..

**Examples:**

Input:n = 2Output:0, 1Input:n = 9Output:0, 1, 1, 2, 3, 5, 8, 13, 21

**Approach:**

- Create a class for the Fibonacci Series
- Take the first two terms of the series as public members a and b with values 0 and 1, respectively.
- Create a generate() method in this class to generate the Fibonacci Series.
- Create an object of this class and call the generate() method of this class using that object.
- The Fibonacci Series will get printed.

Below is the implementation of the above approach:

`// C++ Program to print Fibonacci ` `// Series using Class template ` ` ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// Creating class for Fibonacci. ` `class` `Fibonacci { ` ` ` ` ` `// Taking the integers as public. ` `public` `: ` ` ` `int` `a, b, c; ` ` ` `void` `generate(` `int` `); ` `}; ` ` ` `void` `Fibonacci::generate(` `int` `n) ` `{ ` ` ` `a = 0; ` ` ` `b = 1; ` ` ` ` ` `cout << a << ` `" "` `<< b; ` ` ` ` ` `// Using for loop for continuing ` ` ` `// the Fibonacci series. ` ` ` `for` `(` `int` `i = 1; i <= n - 2; i++) { ` ` ` ` ` `// Addition of the previous two terms ` ` ` `// to get the next term. ` ` ` `c = a + b; ` ` ` `cout << ` `" "` `<< c; ` ` ` ` ` `// Converting the new term ` ` ` `// into an old term to get ` ` ` `// more new terms in series. ` ` ` `a = b; ` ` ` `b = c; ` ` ` `} ` `} ` ` ` `// Driver code ` `int` `main() ` `{ ` ` ` `int` `n = 9; ` ` ` ` ` `Fibonacci fib; ` ` ` `fib.generate(n); ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

**Output:**

0 1 1 2 3 5 8 13 21

## Recommended Posts:

- Print Fibonacci Series in reverse order
- C/C++ Program for nth multiple of a number in Fibonacci Series
- Program to print first n Fibonacci Numbers | Set 1
- Program to print Fibonacci Triangle
- K- Fibonacci series
- n'th multiple of a number in Fibonacci Series
- Factorial of each element in Fibonacci series
- Find the Nth element of the modified Fibonacci series
- TCS Coding Practice Question | Fibonacci Series
- Python | Find fibonacci series upto n using lambda
- Sum of nth terms of Modified Fibonacci series made by every pair of two arrays
- Print Fibonacci sequence using 2 variables
- Print first n Fibonacci Numbers using direct formula
- C Program for Fibonacci numbers
- Program for Fibonacci numbers

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.