Java Tutorials Series - Factorial program using Recursion
Recursion is basically an Algorithm in Java. If we call a method from inside the same method, we get a StackOverflow error in stack trace. It is always recommended not to use recursion but in some conditions it can be very helpful. Let's now look at Factorial program below.
Factorial Program using Recursion -
Factorial logic as you might already know -
4! = 4*3*2*1 = 24
5! = 5*4*3*2*1 = 120
and the series go on...
public class Maths {
public static void main(String[] Args) {
System.out,println(factorial(5)) ;
private static int factorial(int value) {
if(value==1) {
return 1;
}
return(factorial(value - 1) * value);
}
}
//output of the above program is 125
//output of the above program is 125
That's it! the above code demonstrates the factorial program using Recursion. Another great example of this algorithm is implemented in The Tower of Hanoi.
This post is being written at the time when there is pandemic all over the world and we are locked down in our homes. I would urge everyone to make use of this opportunity and grab some skills. Our organisation has come up with an initiative to provide trainings for its employees. I have been going through FSD training and will soon come up with FSD topics such as -
- HTML5
- CSS3
- Javascript
- JQuery
- Bootstrap
- Unix
- PL SQL
- Database concepts
- Core Java (almost completed)
Comments
Post a Comment