Written by Contributors on May 30, 2013 in Java > Programming

Java Program to find nth Fibonaci number using recursion

GET ALERTS:

Get our Latest updates delivered to your mailbox!

This article has been written by our guest author Sravani. This is our first ever guest post, Thank you Sravani!! You can also contribute to ProgrammingUnit.com by just filling the details here or mailing us directly at: admin [at] programmingunit.com

In this post, we will show you how to display the nth Fibonaci number using recursion. The Fibonacci sequence is defined by the following rule:

The first two values in the fibonacci sequence are 0 and 1. Every subsequent value is the sum of the two values preceding it and Recursion is a process in which a function calls itself.

Java Program to find nth fibonacci number using recursion


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class fibrec 
{
	public static void main(String[] args) throws IOException
	{
		System.out.print("\nEnter the value of n : ");
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		System.out.println("\n"+n+"th value in fibonacci series is : "+fibrec(n));
		
	}
	public static int fibrec(int n)
	{
		if(n==1)
		{	
			return 0;
		}
		if(n==2)
		{
			return 1;
		}
		return fibrec(n-1)+fibrec(n-2);
		
	}

}

When the method fibrec() is called, the flow is transferred to the method fibrec(). The fibrec() method takes an integer (Let it be n) as input and returns the value of fibrec(n-1)+fibrec(n-2) to the main function.

To understand the concept of recursion let us consider an example to find the 5th nber in the series, n value is 5
The statement, return fibrec(n-1)+fibrec(n-2) is calculated by substituting n=5.
[Fibrec(4)+fibrec(3)]
[(Fibrec(3)+fibrec(2))+(fibrec(2)+fibrec(1))]
As we already know that fibrec(1) = 0 and fibrec(2) = 1, substitute the respective values
[(fibrec(2)+fibrec(1))+(fibrec(2))+(fibrec(2)+fibrec(1))]
[(1+0)+(1)+(1+0)] = 3.
So the 5th in the series is 3.

Output:
Java Program to find nth fibonacci number using recursion

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: