Sunday, December 6, 2020

11WAP to calculate factorial and to compute the factors of a given no. (i)using recursion, (ii) using iteration



11. WAP to calculate factorial and to compute the factors of a given no. (i)using recursion, (ii) using iteration

#include<iostream>

using namespace std;


class cl

{

private:

int no,fl;

public:

void input()

{

fl=1;

cout<<"\nEnter the no: ";

cin>>no;

}

void factorial()

{


if(no==0)

{

cout<<"\n"<<no<<"!= "<<1;

}

else

{

for(int i=no;i>=1;i--)

{

fl=fl*i;

}

cout<<"\n"<<no<<"!= "<<fl;

}

}

int factorial(int n)

{

if(n > 1)

return n * factorial(n - 1);

else

return 1;

}

void factor()

{

cout<<"\nFactors of "<<no<<"= ";

if(no==1)

{

cout<<1;

}

for(int i=2;i<=no;i++)

{

if(no % i ==0)

{

cout<<" "<<i;


}

}

}

void factor(int n,int i)

{

if(n==1)

cout<<"1";

else

{

if(i <= n)

{

if(n%i == 0)

{

cout << i << " ";

}

factor(n,i+1);

}

}

}

};

int main()

{

cl ob;

int ch,n,x;


do

{

    cout<<"\n1.FACTORIAL using Iteration \n2.FACTORIAL using Recursion \n3.Compute FACTORS using Iteration \n4.Compute FACTORS using Recursion \n5.Exit";

cout<<"\nEnter ur Choice: ";

cin>>ch;

switch(ch)

{

case 1:


ob.input();

ob.factorial();

break;


case 2:

cout<<"\nEnter the no: ";

cin>>n;

x=ob.factorial(n);

cout<<"\n"<<n<<"!= "<<x;

break;


case 3:

ob.input();

ob.factor();

break;


case 4:

cout<<"\nEnter the no: ";

cin>>n;

cout<<"\nFactors of "<<n<<"= ";

ob.factor(n,2);

break;


case 5:

cout<<"\nEXIT";

break;


default:

cout<<"\nSorry! Invalid Choice";

}

}

while(ch!=5);


return 0;

}


No comments:

Post a Comment