Java Recursion
In Java, recursion is a process where a method will call itself continuously and the method is called the recursive method. Sometimes the code will become complex to understand.
Example-
public class Simple {
static void recur(){
System.out.println("Recursion");
recur();
}
public static void main(String[] args) {
recur();
}
}
Output-
Example: finite times
public class Simple {
static int count=0;
static void recur(){
count++;
if(count<=5){
System.out.println("Recursion");
recur();
}
}
public static void main(String[] args) {
recur();
}
}
Output-
Example: factorial number
public class Simple {
static int recur(int n){
if (n == 1)
return 1;
else
return(n * recur(n-1));
}
public static void main(String[] args) {
System.out.println("Factorial: "+recur(5));
}
}
Output-