recursion in java
recursion in java
returntype methodname(){
//code to be executed
methodname();//calling same method
}
EXAMPLE 1: INFINITE TIMES
public class RecursionExample1 {
static void p(){
System.out.println("hello");
p();
}
public static void main(String[] args) {
p();
}
}
OUTPUT:
hello
hello
...
java.lang.StackOverflowError
EXAMPLE 2: FINITE TIMES
public class RecursionExample2 {
static int count=0;
static void p(){
count++;
if(count<=5){
System.out.println("hello "+count);
p();
}
}
public static void main(String[] args) {
p();
}
}
OUTPUT:
hello 1
hello 2
hello 3
hello 4
hello 5
BASE CASE
Thebase case(s), or halting case(s), are the
conditions under which a recursive function
stops recurring. The base case is the small
problem we know how to solve. Every
recursive function must have a base case in
order to stop (the base case is the point at
which the recursion halts
RECURSIVE CASE
Recursivecase is the more general case of
the problem we are trying to solve using
recursive function
OUTPUT:
hello 1
hello 2
hello 3
hello 4
hello 5
Java Recursion Example 3: Factorial Number
public class RecursionExample3 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args) {
System.out.println("Factorial of 5 is: "+factorial(5));
}
}
(N * FACTORIAL(N-1));
OUTPUT:
FACTORIAL OF 5 IS: 120
Working of above program:
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120
JAVA RECURSION EXAMPLE 4: FIBONACCI
SERIES
public class RecursionExample4 {
static int n1=0,n2=1,n3=0;
static void printFibo(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibo(count-1); } }
public static void main(String[] args) {
int count=15;
System.out.print(n1+" "+n2);//printing 0 and 1
printFibo(count-2);//n-
2 because 2 numbers are already printed } }
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
EUCLID'S ALGORITHM.
gcd(1440, 408)
gcd(408, 216)
gcd(216, 192)
gcd(192, 24)
gcd(24, 0)
return 24
return 24
return 24
return 24
return 24
public static int hcf(int n1, int n2) {
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1; } }
TOWERS OF HANOI.