Written by Sai Sandeep Thota on July 13, 2013 in Java > Programming

Java Program to Generate Fibonacci Series

GET ALERTS:

Get our Latest updates delivered to your mailbox!

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

{ 2 comments… read them below or add one }

nagendra August 5, 2013 at 2:02 pm

hiiiii…my problem is fibonaceserice…pls rectfyy…0 1 1 2..hw to write programe….

Reply

Sai Sandeep Thota August 9, 2013 at 11:18 pm

Hello,
You can check Fibonacci Series Programs here:
http://www.programmingunit.com/?s=fibonacci

Reply

Leave a Comment

Previous post:

Next post: