C++ program to find factorial of a number. - coderforcoders

Search

Wednesday, 13 March 2019

C++ program to find factorial of a number.

Factorial of a number in C++

Theory:

Factorial of number in C++ is simple program which takes an input from the user and outputs the factorial of that number. Factorial of a number is multiplication of all integer numbers less than and equal to that number. For example if the given number is 4 then the factorial of the number is 4*3*2*1 which is equal to 24.

Logic:

In this program we are using the concepts of class and objects. A factorial is a class declared and int findFactorial() is a member function of the class, which calculates and displays the factorial of the number.This class also consists data members such as, n, i and fact,


for(i=n;i>=1;i--)
fact=fact*i;

Program:

C++ program to find factorial of a number.


#include<iostream>
using namespace std;
class factorial{
public:
int n,i,fact=1;
void findFactorial()
{
for(i=n;i>=1;i--)
fact=fact*i;
cout<<"The factorial of the number is "<<fact<<endl;
}
};
int main()
{
factorial obj1;
cout<<"Please enter a number\n";
cin>>obj1.n;
obj1.findFactorial();
cout<<endl;
return 0;
}

Output 1:
Please enter a number
5
The factorial of the number is 120

Output 2:
Please enter a number
10
The factorial of the number is 3628800

Output 3:
Please enter a number
6
The factorial of the number is 720


No comments:

Post a Comment