Write a Program in C++ to find the Factorial of a Number



Sumit Kar, Timus Rak, Factorial


/*ITERATIVE*/


//Calling the Header File.
#include<iostream>


//Declaring the main function
int main()
{

//Tells the compiler that we'll be using all the standard C++ library functions
using namespace std;
int num,factorial=1;
//Ask for the number.
cout<<"Enter a number to calculate it's factorial"<<endl;
cin>>num;
for(int i=1;i<=num;i++)
{
factorial=factorial*i;
}
cout<<"Factorial of "<<num<<"="<<factorial<<endl;
cin.get();

return 0;
}



/*RECURSION */


#include<iostream>

using namespace std;

int fact(int);
int main(){
int num,f;
cout<<"\nEnter a number: ";
cin>>num;
f=fact(num);
cout<<"\nFactorial of "<<num<<" is: "<<f;
return 0;
}
//recursive function
int fact(int n){
if(n==1)
return 1;
else
return(n*fact(n-1));
}


/*
Summary: Factorial is represented using '!', so five factorial will be written as (5!),n factorial as (n!).Also
n! = n*(n-1)*(n-2)*(n-3)...3.2.1 and zero factorial is defined as one i.e. 0! = 1.
*/


Comments

Popular posts from this blog

Write a Program to Add two 3x3 Matrix using C

C program for Unit Conversion

Write a Program to Add two 5x5 Matrix using C