Write an iterative C/C++ and java program to find factorial of a given positive number.

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n!. Factorial is mainly used to calculate the total number of ways in which n distinct objects can be arranged into a sequence.

For example,

The value of 5! is 120 as
5! = 1 × 2 × 3 × 4 × 5 = 120
 
(5 distinct objects can be arranged into a sequence in 120 ways).
 
The value of 0! is 1

Practice this problem

The iterative version uses a loop to calculate the product of all positive integers less than equal to n. Since the factorial of a number can be huge, the data type of factorial variable is declared as unsigned long.

The implementation can be seen below in C, Java, and Python:

C


Download  Run Code

Output:

The Factorial of 5 is 120

Java


Download  Run Code

Output:

The Factorial of 5 is 120

Python


Download  Run Code

Output:

The Factorial of 5 is 120

The time complexity of the above solution is O(n) and requires constant space.

 
Also See:

Recursive program to calculate factorial of a number

 
Exercise: Efficiently print factorial series in a given range