## Factorial program in c++

In this C++ program, we are going to determine the factorial of a number using functions. Here I will provide you different ways to find the factorial of a number in c++. First, we use for loop, then functions, and at last recursion.

## Factorial program in c++ using for loop.

Source code:

#include<iostream.h>

#include<conio.h>

void main()

{

int num,i;

clrscr();

cout<<"n Enter a Number:";

cin>>num;

for(i=num-1;i>=1;i--)

num=num*i;

cout<<“n factorial of a number”;

cout<<“n entered by you”;

cout<<num;

getch();

}

__Output:__## Factorial program in c++ using functions

Source code:

#include<iostream.h>

#include<conio.h>

void factorial(int s);

void main()

{

clrscr();

int num;

cout<<"n Enter a number:";

cin>>num;

factorial(num);

getch();

}

void factorial(int s)

{

int fact=1;

for(int i=s;i>=1;i--)

fact*=i;

cout<<"Factorial of "<<s;

cout<<" is "<<fact;

}

Output:

**Enter a number:6**

**Factorial of 6 is 720**

## Factorial program in c++ using recursion

Source code:

#include<iostream.h>

#include<conio.h>

int factorial(int s);

void main()

{

clrscr();

int num,fact;

cout<<"n Enter a number:";

cin>>num;

fact=factorial(num);

cout<<"Factorial of "<<num;

cout<<" is "<<fact;

getch();

}

int factorial(int s)

{

int fact_num;

if(s==1)

return(1);

else

fact_num=s*factorial(s-1);

return(fact_num);

}

Output:

`Enter a number: 5`

`Factorial of 5 is 120`

**Factorial**:

5! =5*4*3*2*1 = 120

n! = n*(n-1)*n-2)*…..*1

## Algorithm to make a C++ Program to Find Factorial of a Number

- Let the number given by the user is “n”.
- Now we initialize loop counter with one less than the number given by the user “i= n-1”.
- The testing condition will be that the loop counter should be greater than and equal to 1 “i>=1″.
- Now we have to decrease the value of i by one “i=i-1” or “i–“.
__for(i=n-1;i>=1;i–)__- We will multiply num by i and stores its value in num.
- num=num*i;
- we have to just print the value of num which will print the factorial of that number entered by the user.

**About this blog post:**

**In this post, I have covered many methods to determine the factorial of a number in c++.**

I hope you enjoy this program as much as I enjoy offering this program to you. If you have any questions or queries related to this program, please don’t hesitate to comment below.

Show Comments