Factorial of a number - C++

Program :
#include<iostream>
using namespace std;
int fr(int n);
   
int main()
{
 int n,fact=1,c,f,k=1;
 cout<<"Enter the number:";
 cin>>n;
 while(k==1)
 {
   cout<< "MENU\n\n1.USING ITERATION\n\n2.USING RECURSION\n\n3.EXIT\n\nENTER YOUR CHOICE:";
   cin>>c;
   switch(c)
    {
 
        case 1: if(n==0)
                cout<<"Factorial of 0 is 1";
               else
                 {
                 for(int i=1;i<=n;++i)
                    fact=fact*i;
                 cout<<"\nfactorial= "<<fact<<"\n\n";
                 }
                 break;
         case 2: f=fr(n);
                 cout<<"\nfactorial="<<f<<"\n\n";
                 break;
         case 3:k=0;
                break;
                
        default:cout<<"\nInvalid choice";
                break;
      }
   }
 return 0;
  
 }
 int fr(int n)
 {
   if(n==0)
    return 1;
   else
    return (n*fr(n-1));
  }

Output:
students@cselab-desktop:~$ g++ fact.cpp
students@cselab-desktop:~$ ./a.out
Enter the number:5
MENU

1.USING ITERATION

2.USING RECURSION

3.EXIT

ENTER YOUR CHOICE:1

factorial= 120

MENU

1.USING ITERATION

2.USING RECURSION

3.EXIT

ENTER YOUR CHOICE:2

factorial=120

MENU

1.USING ITERATION

2.USING RECURSION

3.EXIT

ENTER YOUR CHOICE:3
students@cselab-desktop:~$

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...