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++
Enter an integer number: 6
Factorial of 6 is = 720
What is factorial?
Answer:
Factorial !
Example: 4! is shorthand for 4 × 3 × 2 × 1
| The factorial function (symbol: !) says to multiply all whole numbers from our chosen number down to 1. Examples: |
We usually say (for example) 4! as "4 factorial", but some people say "4 shriek" or "4 bang"
Calculating From the Previous Value
We can easily calculate a factorial from the previous one:
As a table:
n | n! | | |
---|
1 | 1 | 1 | 1 |
2 | 2 × 1 | = 2 × 1! | = 2 |
3 | 3 × 2 × 1 | = 3 × 2! | = 6 |
4 | 4 × 3 × 2 × 1 | = 4 × 3! | = 24 |
5 | 5 × 4 × 3 × 2 × 1 | = 5 × 4! | = 120 |
6 | etc | etc | |
- To work out 6!, multiply 120 by 6 to get 720
- To work out 7!, multiply 720 by 7 to get 5040
- And so on
Example: 9! equals 362,880. Try to calculate 10!
10! = 10 × 9!
10! = 10 × 362,880 = 3,628,800
So the rule is:
n! = n × (n−1)!
Which says
"the factorial of any number is that number times the factorial of (that number minus 1)"
So 10! = 10 × 9!, ... and 125! = 125 × 124!, etc.
What About "0!"
Zero Factorial is interesting ... it is generally agreed that 0! = 1.
It may seem funny that multiplying no numbers together results in 1, but let's follow the pattern backwards from, say, 4! like this:
And in many equations using 0! = 1 just makes sense.
Example: how many ways can we arrange letters (without repeating)?
- For 1 letter "a" there is only 1 way: a
- For 2 letters "ab" there are 1×2=2 ways: ab, ba
- For 3 letters "abc" there are 1×2×3=6 ways: abc acb cab bac bca cba
- For 4 letters "abcd" there are 1×2×3×4=24 ways: (try it yourself!)
- etc
The formula is simply n!
Now ... how many ways can we arrange no letters? Just one way, an empty space:
So 0! =
1