Core JavaJava

fibonacci series in java

This post addresses the following :

– What is Fibonacci sequence
– Write a java program for Fibonacci sequence
– Fibonacci sequence in java

 

Fibonacci Series
 
Fibonacci series is a list of numbers, where next value in the series is the sum of previous two values.

 

In function notation, it is represented as :

f(n) = f(n-1) + f(n-2)

 

The only constraint here is n must be greater than zero.

The special initial values, f(0) and f(1) are defined as :

f(0) = 0 and f(1) =1

 

Therefore,

f(2) = f(1) +f(0) = 1

f(3) = f(2) + f(1) = 2

The Fibonacci numbers, f(n) for n = 0,1,2,.. are:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

 

In this post, we will write a program to return the nth value of a Fibonacci sequence using recursion.

For recursive approach, the nth value in a Fibonacci sequence will be represented as :

Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2)

Fibonacci(1) = 1

Fibonacci(0) = 0

An Illegal Argument exception will be thrown for any n < 0

Here is the complete program :
 

Running this program will result in output :

Fibonacci(10) = 55

 

© 2015, www.techkatak.com. All rights reserved.