Thursday, 23 June 2011

Java Program to Print the Fibonacci series up to desired no

Open notepad or any text editor and type this code.

import java.io.*;
  class fibonacci
   {
    public static void main(String args[]) throws IOException
      {
      BufferedReader ob=new BufferedReader(new InputStreamReader(System.in));
      System.out.print("Enter the length of series: ");
      String d=ob.readLine();
      int j=Integer.parseInt(d);

        int a,b,c;
        a=0;
        b=1;
        c=0;
        System.out.println(a);
            System.out.println(b);
        for(int i=0;i<(j-2);i++)
         {
              c=a+b;
          System.out.println(c);
          a=b;
          b=c;
         
         }
       }
   }


and save this file as fibonacci.java in the bin directory (c:\j2sdk1.4.2\bin).

Now open command prompt and go to your Java directory.
Now compile your  program by typing  javac fibonacci.java
Now the program will be compiled.
Now Run your program by typing  java fibonacci

The output of the above program will be like this.




No comments:

Post a Comment