Write a 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 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 x 2 x 3 x 4 x 5 = 120

(5 distinct objects can be arranged into a sequence in 120 ways).

The value of 0! is 1

The iterative version simply use a for or a while 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.

## C

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <stdio.h> // Iterative function to find factorial of a number using for loop unsigned long factorial(int n) { unsigned long fact = 1; int i; for (i = 1; i <= n; i++) fact = fact * i; return fact; } // Program to find factorial of a number int main() { int n = 5; printf("The Factorial of %d is %lu", n, factorial(n)); return 0; } |

`Output: `

The Factorial of 5 is 120

## Java

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Factorial { // Recursive function to find factorial of a number public static long factorial(int n) { long fact = 1; for (int i = 1; i <= n; i++) fact = fact * i; return fact; } // Program to find factorial of a number public static void main(String[] args) { int n = 5; System.out.println("The Factorial of " + n + " is " + factorial(n)); } } |

`Output: `

The Factorial of 5 is 120

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

**Also See: ** Recursive program to calculate factorial of a number

**Exercise: ** Efficiently print factorial series in a given range

**Thanks for reading.**

Please use ideone or C++ Shell or any other online compiler link to post code in comments.

Like us? Please spread the word and help us grow. Happy coding 🙂

## Leave a Reply