Java Program to Generate Fibonacci Series

We have already written Java Program to find nth Fibonacci Number using Recursion and without using Recursion. Now in this program we are going to print Fibonacci series or sequence upto a given Range.

Here we are using 5 variables. f1, f2, f3 are used to generate Fibonacci Series and n is used for iteration. We first store f2 value in f1 (f1=f2) then f3 in f2 (f2=f3) and then store the sum of f1 and f2 in f3.

Java Program to Generate Fibonacci Series

import java.util.Scanner;

class Fib {
	public static void main(String args[])
	{
		int n, f1, f2=0, f3=1, sum=0;
		System.out.println("Enter Range:");
		Scanner in = new Scanner(System.in);
		n = in.nextInt();
		System.out.println("Fibonacci Series between 1 and "+n+" : ");
		for(int i=0;i<n;i++)
		{
			System.out.print(f3+" ");
			f1=f2;
			f2=f3;
			f3=f1+f2;
			sum=sum+f2;
		}
		System.out.println();
		System.out.println("Sum = "+sum);
	}
}

Output:
Java Program to Generate Fibonacci Series

Leave a Reply