**recursion**or

**loop**. The factorial of a number is equal to number*fact(number-1), which means its a recursive algorithm and that's why it is often used to teach recursion to programmers in computer programming classes.

But, recursion is not always preffered in production code and that's why you also need to learn how to convert a recursive algorithm to an iterative algorithm i.e. algorithm which make use of various loop construct in Java programming language.

Here in this Java beginners tutorial, I'll teach you both ways to calcualte factorial in Java i.e. with and without recursion. Since recursive algorithm is very simple, we'll fisrt look at that and later we'll check out how to calculate factorial without recursion.

##
__Factorial in Java Using Recursion__

You can use following code to find the factorial of a given number in Java. This method uses recursion to do its job. A function is said to be recursive if it calls itself. In order ot create a recursive algorithm, you need a base case without that your program will never terminate.It's the base case where recursion starts to wind down and perform calculation. An incorrect recursive algorithm or base case may result in StackOverFlowError in Java.

/** * Java method to calculate factorial using recursion * @param number * @return factorial of given number */ public static long factorial(int number){ if(number <= 1){ return 1; } return number * factorial(number - 1); }

You can see in this program there is no for or while loop, but this program calls itself see. factorial(number -1), that's why we say this method is using recursion. Where is the base case? Well the if condition you see, which returns 1 if number is less than or equal to 1 is our base case. Why? because factorial of zero or 1 is always 1.

In each run of this method you keep call factorial() method but number reduces by 1 e.g. if you calcualte factorial(4) then method will subsequently call factorial(3), factorial(2) and factorial(1). In the last call the conditional if block will execute and it will return 1, preventing another recursive call. From there onwards, factorial(2) will return 2, factorial(3) will return 6 and factorial(4) will return 24 and method will complete its run.

##
__Factorial in Java Without Recursion__

Now, you know the logic aobut how to calcualte the factorial of a number in Java, you can write your own algorithm which make use of loop instead of recursion. Since factorial is nothing but multiplying the number*number(-1)*(number-2) * .... *1, you can use a loop starting from number itself and going till 1, since factorial(1) is 1, you can stop the loop there. In each step, we multiply numbers and when the loop finish we have the factorial of number as shown below.

/** * Java method to calculate factorial using iteration and loop * @param number * @return factorial of number without iteration */ public static long factorialUsingLoop(int number){ int factorial = 1; for(int i= number; i> 0; i--){ factorial = factorial * i; } return factorial; } }

You can see that we are not calling the factorial() method anymore from the factorial() itself, hence this is not a recursive method.

##
__Java Program to Calculate Factorial in Java__

import java.util.Scanner; /* * Java Program to calculate factorial in Java */ public class Factorial { public static void main(String[] args) { System.out.println("Enter then number : "); // using Scanner to read input from command prompt Scanner commandPromptReader = new Scanner(System.in); int number = commandPromptReader.nextInt(); long factorial = factorial(number); System.out.println("Factorial of number calcualted using recursion: " + factorial); long fact = factorialUsingLoop(number); System.out.println("Factorial of number without recursion: " + fact); // closing scanner to avoid resource leak commandPromptReader.close(); } /** * Java method to calculate factorial using recursion * * @param number * @return factorial of given number */ public static long factorial(int number) { if (number <= 1) { return 1; } return number * factorial(number - 1); } /** * Java method to calculate factorial using iteration and loop * * @param number * @return factorial of number without iteration */ public static long factorialUsingLoop(int number) { int factorial = 1; for (int i = number; i > 0; i--) { factorial = factorial * i; } return factorial; } }

###
__Testing of program__

Just run the program by right clicking on Eclipse and choosing the option "Run as Java Program". If you want to run from command prompt than you need to go to the folder where Eclipse has created the class file for this program and their you need to run the Java command. **Here is the output of program**

Enter then number :

5

Factorial of number calculated using recursion: 120

Factorial of number without recursion: 120

So, this was the simple

*Java program to calcualte factorial of a given number.*It is one of the first programming exercise you will do. It so popular among beginners that almost all kind of computer programming courses use this to teach recursion to their students.

## No comments:

## Post a Comment