The factorial function is a mathematical formula represented by an exclamation mark "!". In the Factorial formula you must multiply all the integers and positives that exist between the number that appears in the formula and the number 1.

"the factorial of any number is that number times the factorial of (that number minus 1)"

#### Here’s an example:

5! = 1 * 2 * 3 * 4 * 5 = 120On this formula number 5 will be called 5th factorial and multiplied by all the numbers that appear on the example until number 1.

#### Calculating From the Previous Value (Recursive Program)

We can easily calculate a factorial from the previous factorial valueTo work outSo the rule is:5!, multiply5by4!to get120here4! = 1*2*3*4 = 24

To work out4!,multiply4by3!to get24here3! = 1*2*3 = 6

To work out3!, multiply3by2!to get6here2! = 1*2 = 2

To work out2!, multiply2by1!to get2here1! = 1

To work out1!, multiply1by0!to get1here0! = 1

n! = n × (n−1)!Which says

"the factorial of any number is that number times the factorial of (that number minus 1)"

So 7! = 7 × 6!, ... and 123! = 123 × 122!, etc.

### Example: C++ program to find factorial

For loop runs from 1 to n. For each iteration of the loop, factorial is multiplied with i. Then the final value of factorial is the product of all numbers from 1 to n.#### Output

Enter a positive integer: 5

Factorial of 5 is 120

### Example: C++ program to find factorial using a function

For loop runs from 1 to n. For each iteration of the loop, factorial is multiplied with i. Then thefinal value of factorial is the product of all numbers from 1 to n.#### Output

Enter a positive integer: 5

Factorial of 5 is 120

### Example: C++ program to find factorial using a Recursive Program

If the number is 0 or 1 then factorial() returns 1. If any other number, then factorial() recursively calls itself with the value n-1*i.e factorial(n-1).*#### Output

Enter a positive integer: 5

Factorial of 5 is 120

## Post a Comment