Tuesday, July 21, 2009

Java Program for Fibonacci Series, Fibonacci Series Example in Java

Welcome back to Java Code Online. Today I am going to give you the Java code for generating Fibonacci Series up to a particular number. A Fibonacci Number is one which is the sum of previous two numbers in that series.

A Fibonacci series always starts with 0, 1 and then the sum of last two digits in the series i.e 0 1 1 2 3 5 8 13 21.... This is an example of a Fibonacci series.

This Java Code asks for a number till which the Fibonacci series is to be generated, and then generates the Fibonacci series up till that number.

The Java code is shown below:-

import java.io.*;

public class Fibonacci {
public static void main(String[] args)
{
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
System.out.println("Enter the number till which Fibonnaci Series is desired:");
int num;
try {
num = Integer.parseInt(br.readLine());
getFibonnaci(num);
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

static void getFibonnaci(int fibonnaci)
{
System.out.println("The Fibonnaci Series till "+fibonnaci+" is:-");
System.out.print("0 ");
int f1 =0, f2 = 1,f3;
while(f2 <=fibonnaci){
System.out.print(f2+" ");
f1 = f1 + f2;
f3 = f2;
f2 = f1;
f1 = f3;
}
}
}

I hope the code for generating the Fibonacci series is helpful to you all. If you like the post useful, then do leave a comment. For more info on Java, keep buzzing Java Code Online.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.