Wednesday, February 21, 2024

WAP to display Fibonacci series (i)using recursion, (ii) using iteration

 #include<iostream>

using namespace std;


class cl

{


public:

int a=0,b=1,l;

void input()

{


cout<<"\nEnter the Length of Fibonacci series: ";

cin>>l;

}

void fib()

{


for(int i=0;i<l;i++)

{

int c=a+b;

cout<<" "<<a;

a=b;

b=c;

}

}

int fib(int x)

{

if((x==1)||(x==0))

{

return(x);

}

else

{

return(fib(x-1)+fib(x-2));

}

}

};

int main()

{

cl ob;

int ch,n,i=0;



do

{

  cout<<"\nFibonacci series \n\n1.using Iteration \n2.using Recursion\n3.Exit";  

cout<<"\nEnter ur Choice: ";

cin>>ch;

switch(ch)

{

case 1:

ob.input();

ob.fib();

break;


case 2:

ob.input();

cout << "\nFibonnaci Series : ";

i=0;

while(i<ob.l)

{

cout << " "<<ob.fib(i);

i++;

}

break;


case 3:

cout<<"\nEXIT";

break;


default:

cout<<"\nSorry! Invalid Choice";

}

}

while(ch!=3);


return 0;

}

No comments:

Post a Comment