Friday 19 July 2013

04 . Write C++ programs to find factorial by using recursive and non-recursive functions

a ).  To find the factorial of a given integer using Recursion .



#include<iostream.h>   //If you are using gcc compilers like PUTTY, DEV C++, ECLIPSE C++
                                         //kindly use #include<iostream>
                                         //There is no #include<conio.h> header file in gcc
#include<conio.h>           //using namespace std;( recommended if you are using gcc )
int factr(int);                    //finds factorial Using Recursion
int factnr(int);                  //to find factorial Using Non-recursion

int main()
{

    int result,n,res;
    char ch;
    clrscr();                        //gcc does't include this function (it uses conio.h Header)
    cout<<"enter 'n' value to find factorial : ";
    fact:                               //"fact:" is a label to correct -ve values from input ( variable - 'n' ).
                                          //I have implemented this by using goto control structure
    cin>>n;

    if(n>=0)
    {
        cout<<"\nenter 'r' to solve by recursion";
        cout<<"\nenter 'n' to solve by non recursion"<<endl;
        ch:                            //"ch: " is a label to correct your wrong choice of selection (variable- 'ch')
        cin>>ch    ;
    if(ch=='r')
        {
            cout<<"\nRecusive Method is selected for execution"<<endl;
            k=factr(n);
            cout<<"\nfactorial of "<<n<<" is:"<<k<<endl;
        }
    else if(ch=='n')
        {
        k=factnr(n);
        cout<<"\nfactorial of "<<n<<" is:"<<k<<endl;
        }
        else
  
      {
        cout<<"\nmake a valid choice";
        goto ch;                           //CAUTIOUS while using goto in your program                             
                                               //Same result can be achieved by SWITCH contol structure
        }
    }
    else
        {
        cout<<"enter a valid positive integer";
        goto fact;
        }
        getch();                             //gcc does't include this function (it uses conio.h Header)

     return 0;
}
int factnr(int n)                        //Non - Recursive function for factorial
{
  
    int f=1,i;
    cout<<"\nNon recusive Method is selected for execution"<<endl;
    for(i=1;i<=n;++i)
    f=f*i;
    return f;
}
int factr(int n)                         
//Recursive function for factorial                         
{
    if(n==0)
    return 1;
    else
    return n*factr(n-1);
}

output:
enter 'n' value to find factorial -4
enter a valid positive integer-3
enter a valid positive integer3

enter 'r' to solve by recursion
enter 'n' to solve by non recursion
f

make a valid choice
s

make a valid choice
r

Recusive Method is selected for executionfactorial of 3 is:6
//Please write your opinion and comments below

No comments:

Post a Comment