Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

simplesnippets.

tech

Recursion Working

Recursion in Java is a process in which a method calls itself continuously. Using


recursive algorithm, certain problems can be solved quite easily.
Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder
Tree Traversals, DFS of Graph, etc.  A method in java that calls itself is called recursive
method.

How does Recursion work in Java ?


simplesnippets.tech

Working of Recursive Methods –


 In the above program, recursiveMethod() method is called from inside
the main method at first (normal method call).
 Also, recursiveMethod() method is called from inside the same
method, recursiveMethod(). This is a recursive call.
 The recursion continues until some condition is met to prevent it from
execution. If not, infinite recursion occurs.
 Hence, to prevent infinite recursion, if…else statement (or similar
approach) can be used where one branch makes the recursive call
and other doesn’t.

Recursive Program example to Find Factorial of a


Number –

public class FactorialExample {

static int fact(int n)


{
if(n!=1)
{
return n*(fact(n-1));
}
else
{
return 1;
}
}
public static void main(String[] args)
simplesnippets.tech

{
System.out.println("Factorial of 4 is: "+fact(4));
}
}
simplesnippets.tech
simplesnippets.tech

Fibonacci series 1,1,2,3,5,8

public class recursion


{
public static int foo(int y)
{
if (y <=1) F [5]
return 1;
else
return foo(y-1)+foo(y-2);
}
public static void main(String[] args)
{
System.out.println(foo(5));
} }

F[5]

F[4] F[3]

F[3] F[2] F[2] F[1]

F[2] F[1] F[1] F[0] F[1] F[0]

F[1] F[0]
simplesnippets.tech

You might also like