C++ program to print Fibonacci series up to N using class

Given the value of N, we have to print Fibonacci series up to n using the class and object approach.
Submitted by Shubh Pachori, on September 09, 2022

Example:

Input:
Enter n : 8

Output:
Fibonacci series upto 8 terms is 0,1,1,2,3,5,8,13,

C++ code to print Fibonacci series up to N using the class and object approach

#include <iostream>
using namespace std;

// creating a class
class Fibonacci {
  // private data member
 private:
  int number;

  // public member function
 public:
  // getN() function to insert n
  void getN() {
    cout << "Enter n : ";
    cin >> number;
  }

  // fibonacci() function to print 
  // fibonacci series upto n
  void fibonacci() {
    // initialize first and second terms
    int term_1 = 0, term_2 = 1;

    // initialize the next term (3rd term)
    int term_3 = term_1 + term_2;

    // print the base line
    cout << "Fibonacci series upto " << number << " terms is ";

    // print the first two terms t1 and t2
    cout << term_1 << "," << term_2 << ",";

    // for loop to print fibonacci series 
    // upto entered term
    for (int index = 3; index <= number; index++) {
      // print third term
      cout << term_3 << ",";

      // copy previous term to second previous term
      term_1 = term_2;

      // copy just last term to the previous one
      term_2 = term_3;

      // now make a new term with the updated terms
      term_3 = term_1 + term_2;
    }
  }
};

int main() {
  // creating object
  Fibonacci F;

  // calling getN() function to insert n
  F.getN();

  // calling fibonacci() function to 
  // print fibonacci series
  F.fibonacci();

  return 0;
}

Output:

Enter n : 10
Fibonacci series upto 10 terms is 0,1,1,2,3,5,8,13,21,34,

Explanation:

In the above code, we have created a class Fibonacci, one int type data member number to store the number n, and public member functions getN() and fibonacci() to store n and to print Fibonacci series upto n.

In the main() function, we are creating an object F of class Fibonacci, reading a number n by the user using getN() function, and finally calling the fibonacci() member function to print the Fibonacci series up to n. The fibonacci() function contains the logic to print the Fibonacci series up to n.

C++ Class and Object Programs (Set 2) »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.