Friday 19 July 2013

04. Write C++ programs to find Fibonacci number in both recursive and non-recursive functions

((((((Don't copy and paste it. Please Practice . These programs are provided to create interest in Students))))))))

/* Fibonacci series is Staring with 0, 1 remaining series is obtained by adding previous two numbers */
/*in general fibonacci series starts from 0, but they have given instruction as it is starting with 1, 1
so I have followed the instructions from Authority */

#include<iostream>
using namespace std;

void fibnr(int );

int fibr(int n)
{
        if(n<=2)                          //logic similar to factorial in case of recursion
                 return 1;
        else
                 return (fibr(n-1))+(fibr(n-2));
}
int main()
{
        int n,fibo;
        char ch;
        cout<<"\nenter n value";
        cin>>n;
        while(n<1)                     //validating n value to strictly +ve integer
        {
                cout<<"\nPlease enter a valid +ve integer"<<endl;
                cin>>n;
        }
        cout<<"Enter 'r' to find using recursive method"<<endl;
        cout<<"Enter 'n' to find using Non- Recursive method"<<endl;
        cout<<"Please enter your choice :";
        cin>>ch;
        switch(ch)
        {
        case 'n':
                fibnr(n);
                break;
        case 'r':
                fibo=fibr(n);
                cout<<"\n"<<n<<"th fibonacci number is : "<<fibo;
                break;
        default:
                cout<<"Invalid choice"<<endl;
        }
        return 0;
}
void fibnr(int n)
{
        int fib1=0,fib2=1,fibo,i;         //Actual fibonacci starts with 0, 1 .though I've neglected '0'.
        for(i=0;i<n;++i)
        {
        fibo=fib1+fib2;
        fib1=fib2;
        fib2=fibo;
        }
        cout<<"\n"<<n<<"th fibonacci number is :"<<fib1;
}

No comments:

Post a Comment