Fibonacci series in JAVA

By definition Fibonacci series in defined as the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two.i.e the nth number is obtained by adding the n-1 and n-2 number in the series.
Let us consider an example:Assume that we need to make a series of 5 numbers.As it is fixed the first two places are occupied by 0 and 1.The third number in the series in obtained by adding the first and second numbers,therefore the third number will be 1….fourth number will be addition of second and third number…..so it will be 2….hence the final number in the series is addition of fourth and third number….hence the final number in the series is..3.
Now let us write a java program to print the Fibonacci series of length given by user.To get an input statement from user we need use the object of Scanner class.

import java.util.Scanner;    //java package which contains details about Scanner class
class fib
{
  public Static void main(String arg[])
    {
        int a=0,b=1,c;
        System.out.print("Enter the length of the series needed including 0,1:");
        Scanner ob=new Scanner(System.in);        //declaration of object for Scanner class
        int n=ob.nextInt();           //Initializing the value of n 
        System.out.print("Fibonacci series is:"+ a + " " + b);
        for(int i=0;i<=n-2;i++)
         {
             c=a+b;               //getting the nth number by adding n-1,n-2 numbers.
             a=b;
             b=c;
             System.out.println(" " + c);
         }   //ending the for loop
     }   //ending the main function
}   //ending the class

Output:fib
You can be download the source code:download

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in Java and tagged , , , , . Bookmark the permalink.

1 Response to Fibonacci series in JAVA

  1. Reblogged this on Researcher's Blog and commented:
    Fibonacci series in JAVA

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s