code of fibonaci series using recursion in java code example
Example: fibonacci sequence java using recursion
import java.io.*;
public class Fibonacci_JeffreyHuang
{
public static long Fibonacci (long n)
{
if (n == 1 || n == 2)
{
return 1;
}
else if (n <= 0)
{
System.out.println ("Error: There is no term less than 1");
return 0;
}
else
{
return (Fibonacci (n - 1) + Fibonacci (n - 2));
}
}
public static void main (String[] args) throws IOException
{
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
String sentinel = "yes";
long fib_term = 0;
boolean invalid;
while (sentinel.equalsIgnoreCase ("yes") || sentinel.equalsIgnoreCase ("y"))
{
System.out.println ("Which fibonacci term would you like to find?");
invalid = true;
while (invalid == true)
{
invalid = false;
try
{
fib_term = Integer.parseInt (br.readLine ());
}
catch (Exception e)
{
System.out.println ("Invalid input. Please try again.");
System.out.println ();
invalid = true;
}
}
System.out.println ();
if (fib_term <= 0)
{
Fibonacci (fib_term);
}
else
{
System.out.println ("Term " + fib_term + " of the fibonacci sequence is " + Fibonacci (fib_term));
}
System.out.println ();
System.out.println ("Would you like to run the program again? (y/n)");
System.out.println ();
sentinel = br.readLine ();
System.out.println ();
while (!(sentinel.equalsIgnoreCase ("yes") || sentinel.equalsIgnoreCase ("y")
|| sentinel.equalsIgnoreCase ("n") || sentinel.equalsIgnoreCase ("no")))
{
System.out.println ("Invalid input. Please try again.");
System.out.println ("Would you like to run the program again? (y/n)");
sentinel = br.readLine ();
System.out.println ();
}
}
System.out.println ("Program terminated by user.");
}
}