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

Java Program to find nth Fibonaci number using recursion


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)
			return 0;
			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.
As we already know that fibrec(1) = 0 and fibrec(2) = 1, substitute the respective values
[(1+0)+(1)+(1+0)] = 3.
So the 5th in the series is 3.

Java Program to find nth fibonacci number using recursion

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: