Home »
C++ programs »
C++ Most popular & searched programs
C++ program to find factorial of a number
In this program, we will learn how to find factorial of a given number using C++ program? Here, we will implement this program with and without using user define function.
Logic:
- Input a number
- Initialize the factorial variable with 1
- Initialize the loop counter with N (Run loop from number (N) to 1)
- Multiply the loop counter's value with factorial variable
Program to find factorial using loop in C++
#include <iostream>
using namespace std;
int main()
{
int num,i;
long int fact=1;
cout<<"Enter an integer number: ";
cin>>num;
for(i=num;i>=1;i--)
fact=fact*i;
cout<<"Factorial of "<<num<<" is = "<<fact<<endl;
return 0;
}
Output
Enter an integer number: 6
Factorial of 6 is = 720
Program to find factorial using User Define Function in C++
#include <iostream>
using namespace std;
//function declaration
long int factorial(int n);
int main()
{
int num;
cout<<"Enter an integer number: ";
cin>>num;
cout<<"Factorial of "<<num<<" is = "<<factorial(num)<<endl;
return 0;
}
//function defintion
long int factorial(int n)
{
int i,fact=1;
for(i=n;i>=1;i--)
fact=fact*i;
return fact;
}