If we go by the definition factorial of a non-negative integer n is product of all positive integers less than or equal to n.

**As example**

**4! = 4 X 3 X 2 X 1 = 24**

If you see here you need to multiply every time by the number which is one less than the previous one until
you reach 1, which can be considered **base case**. That makes it a very good example for learning **recursive
programming**. In fact **calculating factorial** using recursion is the first program many people will do while
learning recursion apart from another program __How to reverse a string in Java using recursion__.

If there is a **recursive solution** for any problem then there is always a **iterative solution** too so there is
a iterative solution too for calculating factorial. In this post we'll see both ways to calculate factorial.

__Factorial of a number in Java using Iteration __

import java.util.Scanner; public class FactorialItr { public static void main(String[] args) { // get input from user Scanner input = new Scanner(System.in); System.out.println("Enter a number: "); int num = input.nextInt(); int fact = calculateFactorial(num); System.out.println("Factorial of " + num + " is " + fact); } private static int calculateFactorial(int num){ int fact = 1; for(int i = num; i >= 1; i--){ fact = fact * i; } return fact; } }

__Output__

Enter a number: 5 Factorial of 5 is 120

Logic here is to take
__input from console__ and calculate factorial of that number using for loop that ranges
from number till 1 and within the loop keep multiplying the result with the loop counter.

__Factorial of a number in Java using Recursion__

import java.util.Scanner; public class Factorial { public static void main(String[] args) { // get input from user Scanner input = new Scanner(System.in); System.out.println("Enter a number: "); int num = input.nextInt(); int fact = calculateFactorial(num); System.out.println("Factorial of " + num + " is " + fact); } private static int calculateFactorial(int num){ // base case (exit recursion) if(num == 1){ return 1; }else{ return num * calculateFactorial(num - 1); } } }

__Output__

Enter a number: 4 Factorial of 4 is 24

Here again the user is asked to enter a number then the *same method is called recursively using passed
number minus one every time*. **Base case** here is when number becomes 1. Since factorial of 0 and 1 both is 1
so both can be used as base cases.

A word of caution here though, if you are trying to get a factorial of a number more than 16 or 17 then take the type as double or BigInteger otherwise you will get an overflow error.

That's all for this topic **Factorial program in Java**. If you have any doubt or any
suggestions to make please drop a comment. Thanks!

__Related Topics__

**You may also like - **

## No comments:

## Post a Comment