Fibonacci Series in JavaIn mathematics, the Fibonacci numbers are the numbers in the following sequence: 0,1,12,3,5,8,13,21,34,55,89,144 By definition, the first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s. In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation     F_n = F_{n-1} + F_{n-2} with seed values F_0 = 0 and F_1 = 1.

Fibonacci Flowchart

The following flowchart illustrates how to generate Fibonacci Series for the first N numbers.

Fibonacci Flowchart

Fibonacci Generator Program

The following program shows how to generate the Fibonacci Series in Java. It uses recursion to compute the next Fibonacci number.

package com.livrona.snippets.numbers;

/**
 * A simple snippet used to generate the Fibonacci Series up to a given number.
 * 
 * @author java4learners
 * 
 */
public class FibonacciGenerator {

	/**
	 * Generate the Series
	 * 
	 * @param max
	 */
	public static void generate(int max) {

		try {
			for (int i = 0; i < max; i++) {
				System.out.println("Fib No : " + (i+1) + " is " + fibonacci(i));
			}
		} catch (Exception ex) {
			System.out.println("Failed to generated the series :"
					+ ex.getMessage());
			throw new RuntimeException(ex);
		}
	}

	/**
	 * Test Method
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

		if (args.length != 1) {
			System.out
					.println("Usage: java com.livrona.snippets.numbers.FibonacciGenerator <Max Number>");
			System.exit(0);
		}

		// store args
		String maxFibonacciNo = args[0];

		System.out.println("Generate Fibonacci up to : " + maxFibonacciNo);

		// invoke the method
		try {
			generate(new Integer(maxFibonacciNo).intValue());
		} catch (Exception e) {
			System.out.println("Failed to generate the Fabonacci: "
					+ e.getMessage());
			e.printStackTrace();
		}

	}

	/**
	 * Returns the next fibonacci number
	 * 
	 * @param max
	 * @return
	 */
	private static int fibonacci(int max) {

		if (max == 0 || max == 1)
			return max;
		else
			return (fibonacci(max - 1) + fibonacci(max - 2));
	}
}
 

Program Output

Generate Fibonacci up to : 10 Fib No : 1 is 0 Fib No : 2 is 1 Fib No : 3 is 1 Fib No : 4 is 2 Fib No : 5 is 3 Fib No : 6 is 5 Fib No : 7 is 8 Fib No : 8 is 13 Fib No : 9 is 21 Fib No : 10 is 34