`
When a function calls itself directly or indirectly, this process is known as recursion, and the resulting function is known as a recursive function. A recursive algorithm can make some problems relatively simple to solve.
returntype methodname(){
methodname(); //invoking the same method
}
// Java program to add a range of number with Recursion
class Test{ public static int sum(int i) { if(i > 0){ return i + sum(i - 1); } else{ return 0; } } } public class Main { public static void main(String[] args) { Test test=new Test(); System.out.println(test.sum(10)); } }
Output:
55
// Java program to find a factorial with Recursion
class Test{ public static int fact(int i) { if (i == 1) return 1; else return(i * fact(i-1)); } } public class Main { public static void main(String[] args) { Test test=new Test(); System.out.println(test.fact(6)); } }
Output:
720
// Java program to add number between two given number with Recursion
class Test{ public static int sum(int num1, int num2){ if (num2 > num1){ return num2 + sum(num1, num2 - 1); } else{ return num2; } } } public class Main { public static void main(String[] args) { Test test=new Test(); System.out.println(test.sum(1,10)); } }
Output:
55
Post your comment