Thursday, March 8, 2012

A simple program to find factorial of a number

 // A simple program to find factorial of a number
#include<iostream>
using namespace std;

int main()
{
    int  a;
    cout << "\n Enter the no. to find factorial: ";
    cin >> a;


        int fact=1;
        for(int i=1;i<=a;i++)
        {
            fact=i*fact;
        }
   
    cout << "\n\n FACTORIAL= " << fact;
}

____________________________________________________________________________________
// program to find factorial of a number using functions
#include<iostream>
using namespace std;

int factorial(int);                //declaration of a function named factorial

int main()
{
    int fact, a;
    cout << "Enter the no.  to find factorial: ";
    cin >> a;

    fact = factorial(a);
    cout << "\n\n FACTORIAL= " << fact;
   
}

int factorial(int x)               //definition above declared function is given here
    {
        int n=1;
        for(int i=1;i<=x;i++)
        {
            n=i*n;
        }
    return (n);
}

___________________________________________________________________________________
// factorial of 1 to 10 (first 10) natural number
#include<iostream>
using namespace std;

int main()
{
    int  b;
   
    for(b=1; b<=10; b++)
    {
        long int fact = 1;
        for(int i=1;  i<=b;  i++)
        {
            fact=i*fact;
        }
        cout<< "\n\nFACTORIAL of: " << b << " is " << fact;
    }   
}

No comments:

Post a Comment