java program to find n-th fibonacci number using recursion

The Fibonacci numbers are the numbers in the following integer sequence called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones:

The fibonacci series is defined as follows:

0,1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144 , …

Recursive Algorithm for Fibonacci Numbers

Algorithm F(n)

if n ≤ 1 then return n

else return F(n-1) + F(n-2)

 

Full java program is given below:

<pre>import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * java program to find n-th fibonacci number using recursion
 * Created by sani kamal on 07-May-17.
 */
public class Fibonacci {
    public static void main(String[] args) {
        Fibonacci fib = new Fibonacci();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.println("Enter a number:");
            int num = Integer.parseInt(br.readLine());
            System.out.print(num+"th Fibonacci number is:" + fib.fibonacci(num));

        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

    }

    private int fibonacci(int n) {
        if (n < 1)
            return 0;
        else if (n == 1)
            return 1;
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}</pre>
Advertisements

One thought on “java program to find n-th fibonacci number using recursion

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s