Recursion in java
Which Function called by itself that is recursion Function.In that syntax "Function()" called by itself.But It's iterate the function limited. If it's iterate the function long time may be stackoverflow error happens.
Syntax:
Function() { Function(); }
The function "Recursion" is called by it self. It continuously called the function itself.It stop when n==0.
Example-1
public class Main { public static void main(String[] args) { Main obj = new Main(); obj.Recursion(5); } public void Recursion(int n) { if(n!=0) { System.out.println(n); n = n-1; Recursion(n); } } }
Output
5 4 3 2 1
The function "Recursion" is a return type function. It's stop the recursion when n==0.
Example-2
public class Main { public static void main(String[] args) { Main obj = new Main(); obj.Recursion(5); } public int Recursion(int n) { System.out.println(n); if(n!=0) { n = n-1; return Recursion(n); } return n; } }
Output
5 4 3 2 1 0