Tuesday, January 11, 2022

Print nth Fibonacci using java recursion.

 Hey there, 

    We know the fibonacci start with 0, 1, then addition of previous two number. Here next numbers are 1(0+1), 2(1+1), 3(1+2), 5(2+3), 8(3+5), 13(5+8) like wise. 

Here i will post the recursion program for find the Nth fibonacci number. Recursion is calling a method from that method, simple calling itself. 

For Example : 


private static void sayHello(){
System.out.println("Hello !");
return sayHello();
}

If you execute this method we will end up with stackoverflow exception. The exception will
be thrown after jvm stack overloaded,

......... here is lot of Hello ! printed.
Hello !
Hello !
Hello !
Hello !
Exception in thread "main" java.lang.StackOverflowError
	at sun.nio.cs.UTF_8$Encoder.encodeLoop(UTF_8.java:691)
	at java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:579)

Because in this method we don't have any base condition to return this recursion stack trace.
This is very important when you go for recursion we need to have base condition at
first in you implementation.


private static void sayHello(int n){
if(n<1){
return ;
}
System.out.println("Hello !");
sayHello(n-1);
}

Here if condition check n is less than 1, this is our base condition. So now you will get
some idea about how recursion works in java. Let we get in our fibonacci program,


private static long printFibonacci(int n){
if(n<=1){
return n;
}
return printFibonacci(n-1) + printFibonacci(n-2);
}
If user input n is 5 then this program will print 5(0,1,1,2,3,5) the number is start with 0
so we will get 5.
Explanation for printFibonacci() is loading...

No comments:

Post a Comment