C++ Factorial
the factorial of a positive integer number n! is the product of all integers less than or equal to n.
For example :
5! = 5x4x3x2x1.
here's a typical implementation of function using for,while and do-while loop.
i) for loop
#include<iostream>
using namespace std;
int main()
{
int n;
int fac = 1;
cout << " Please enter an Integer : " ;
cin >> n;
cout << " The Factorial of " <<n<< "!= ";
for (n>=0;n>0;n--)
{
fac = fac*n;
cout<<n;
if(n!=1)
cout << " x ";
}
cout << " = " <<fac<<endl;
system ("pause");
return 0;
}
ii) while loop
#include <iostream>
using namespace std;
int main ()
{
int n;
int fac = 1;
cout << "Please enter an integer : ";
cin >> n;
cout << "The factorial of " <<n<< "! = " ;
while (n>0)
{
fac = fac * n;
cout << n;
if(n!=1)
cout << " x " ;
--n;
}
cout << " = " << fac<< endl;
system ("pause" );
return 0;
iii) do-while loop
#include <iostream>
using namespace std;
int main()
{
int n;
int fac = 1;
cout << " Please enter an integer : ";
cin >>n;
cout << " The Factorial of " <<n<< "! = ";
{
do
{
fac = fac*n;
cout <<n;
if (n!=1)
cout << " x ";
n--;
}
while (n>0);
}
cout << " = " <<fac<<endl;
system ("pause");
return 0;
}
Subscribe to:
Posts (Atom)
No comments:
Post a Comment