This article explains recursion and provides programs for calculating factorial with or without recursion.

### Recursion

Recursion is a process of a method calling itself.

Recursion can be used to solve problems where a logic needs to executed repeatedly for a smaller set.

For example, we can recursion to find the factorial of number.

Factorial of a number, n is expressed as n! and can be calculated as :

n! = n * (n-1) * (n-2) … * 2 * 1

Lets first see how to calculate factorial without using recursion.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package firstpackage; public class FactorialWithoutRecursion { public static void main(String[] args) { System.out.println("5! = " + factorial(5)); } private static long factorial(int num){ long fact =1; while(num > 0){ fact *= num--; } return fact; } } |

The output of the above program is :

5! = 120

In the next program, we will calculate factorial in a recursion approach.

This is because factorial of a number can be expressed as follows :

n! = n * (n-1)!

= n * (n-1) * (n-2)!

= n * (n-1) * (n-2) * (n-3)!

…

…

Here is the program to calculate factorial using recursion :

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package firstpackage; public class FactorialUsingRecursion { public static void main(String[] args) { System.out.println("5! = " + factorial(5)); } private static long factorial(int num){ if(num==1) return 1; else return num*factorial(num-1); } } |

The output of the above program is :

5! = 120

© 2015, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post

#