Hi
all , Today I am going to write a post on popular interview program which is Write
a program in java to print Fibonacci series using recursive method.
This
post is actually an extension of my previous post program in java to printFibonacci series which you can find here
.
But
in most of interviews Fibonacci series is asked to print using recursive method
.
So
What is recursive method ????
Actually
as the name signifies a recursive method is one which repeatedly calls itself .While
writing a recursive method the most common mistake programmer do is not to
properly define the end of that method mean on which condition this method will
stop calling itself which can led to Stackoverflow error L
So
Please take care of that mistake .So here is program in java to print Fibonacci
series using recursive method
import
java.util.Scanner;
public class fibonacci {
public static void main(String[]
args) {
Scanner in = new
Scanner(System.in);
System.out.println("please
enter length of series in next line");
int
length=Integer.parseInt(in.nextLine());
for (int i = 1; i
<=length; i++) {
System.out.print("
"+fibo(i));
}
}
public static int fibo(int n)
{
//System.out.println(n+"n");
if(n == 1)
{
return 0;
}
else if(n==2)
{
return 1;
}
else
{
return (fibo(n-1)+fibo(n-2));
}
}
}
|
So this was my post on To print Fibonacci series in java using recursive method.If you have any doubt or you know another efficient method please do write me .If you like this post please comment below :)
you may like :
Java Interview Questions
Difference between equals() and = =
No comments:
Post a Comment