urgent help required.please solve this program.

Status
Not open for further replies.

quan chi

mortal kombat
using constructor write a program in c++ to generate first n terms of fibonacci series.

(you can take n=5)

how to do it using constructor.:confused:
please help.
 

Faun

Wahahaha~!
Staff member
lol..its easy man

just write the whole code in the constructor passing n as an argument.

try it now, probably someone will come up with complete code.
 

redhat

Mad and Furious
Suppose this is some sort of "SCHOOL" Homework!!!
Jus create a parameterized Constructor n accept the value of 'n' within it
Simple!!!!!
 

Garbage

God of Mistakes...
I've not compiled this code and even not programmed C++ for a long time.
Please check this.
The program will be something like -
Code:
 include <iostream>

class factorial
{
    long int fact=1;
    
    factorial (int no)    // This is a constructor with 1 argument
    {
        int store=no;
        for ( ; no <1 ; --no)
            fact*=no;
        cout << "Factorial of " << store << "is " << fact;
    }
}

int main()
{
    int no;
    
    factorial f1(3);    // Direct call
    // User choice
    cout << "Enter a number : ";
      cin >> no;
     
    factorial f(no);
    
    return 0;
}

Sorry, if there are mistakes. :(
 

QwertyManiac

Commander in Chief
As others said, use a default constructor and a parameterized constructor to call some function which outputs the needed.

Code:
#include<iostream>

using namespace std;

class A
{
    int n;

    public:
        void call(int n)
        {
            cout<<"\nFibonacci numbers upto "<<n<<" are: \n";
            int a(1),b(1),t(0);
            for(int i=0;i<n;i++)
            {
                cout<<a<<" ";
                t=b;
                b=a+b;
                a=t;
            }
            cout<<endl;
        }
        
        A()
        {
            cout<<"\nEnter the number of Fibonacci numbers you wish to calculate: ";
            cin>>n;
            call(n);
        }
        
        A(int n)
        {
            call(n);
        }
};

int main()
{
    A *a;
    cout<<"\nDefault constructor call (Asks for user input):\n";
    a =  new A;
    cout<<"\nParameterized constructor call (Assumes input as value passed):\n";
    a = new A(10);
    return 0;
}

Outputs as:
Code:
Default constructor call (Asks for user input):

Enter the number of Fibonacci numbers you wish to calculate: 6

Fibonacci numbers upto 6 are: 
1 1 2 3 5 8 

Parameterized constructor call (Assumes input as value passed):

Fibonacci numbers upto 10 are: 
1 1 2 3 5 8 13 21 34 55
 
Status
Not open for further replies.
Top Bottom