Write Java Program to Print Fibonacci Series upto N Number

Fibonacci Series Example - crunchify.co

In mathematics, the Fibonacci numbers or Fibonacci series or Fibonacci sequence are the numbers in the following integer sequence:  

0,\;1,\;1,\;2,\;3,\;5,\;8,\;13,\;21,\;34,\;55,\;89,\;144,\; \ldots\;

By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two.

In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation

F_n=F_{n-1} + F_{n-2},\!\,

with seed values

F_0=0,\; F_1=1.

Here is a simplest Java Program to generate Fibonacci Series.

Output:

Have anything to add to this article? Please chime in and join the conversion.

Enjoyed this post?

Be sure to subscribe to the Crunchify newsletter and get regular updates about awesome posts just like this one and more! Join more than 8000 subscribers!

  • http://michal.zalecki.pl/ Michał Załęcki

    As recursion is soooo slooooowwww, there is mine (blazing fast, Fibonacci(9999) in under 0.5s):

    
    public static long Fibonacci(int n) {
        long fib2Prev = -1;
        long fibPrev = 1;
        for (int i = 0; i <= n; i++) {
            fibPrev = fib2Prev + (fib2Prev = fibPrev);
            // now fibPrev is "current"
        }
        return fibPrev;
    }
    
  • David Leonhartsberger

    I think the first recurisve implementation is not tail recusive

  • Redman

    I am confused as to the recursive method. The following is in a for loop that starts with i=1:

    fibonacciRecusion(number-1) + fibonacciRecusion(number -2)

    So i=1 & i=2 return 1 & 1 respectively. But continuing on as i is incremented by 1:

    i=3 …. fibonacciRecusion(number-1) + fibonacciRecusion(number -2) = 2 + 1 = 3

    i=4 …. fibonacciRecusion(number-1) + fibonacciRecusion(number -2) = 3 + 2 = 5

    i=5 …. fibonacciRecusion(number-1) + fibonacciRecusion(number -2) = 4 + 3 = 7 ???

    7 is not a fibonacci number — but the program when run prints 8 ???

    Forgive me if I’m missin something obvious, but would you please explain it to me.

    • http://crunchify.com/ App Shah

      Hi Redman – try adding last two values at i=5 ==> 5+3 = 8 :)

      • Redman

        Thanks for the quick reply App.

        But when i=5, isn’t it then (i-1) + (i-2) = (5-1) + (5-2) = 4 + 3 = 7 ?

        How is (number-1) still 5?

  • Koko

    How can I get the sum of all the fibonacci sequence produced?

    • http://crunchify.com/ App Shah

      Will update above code soon with that option.. :)

  • Smirnoff

    you don’t need a third variable

  • mrphi

    What is the plugin for source code ?

    • http://crunchify.com/ App Shah

      I’m using Crayon Syntax Highlighter.

  • Neel Sheyal

    We can reduce the time complexity from exponential to linear by not performing the redundant work of computing Fibonnaci values many times from scratch. We can use the concept of dynamic programming by storing the Fibonacci numbers calculated so far.

    • http://crunchify.com/ App Shah

      Thanks Neel. Could you share your code?

  • kaustab ganguly

    why c=1,b=1,a=0

  • umika

    Hi, I would like whether this method can apply for user number in unordered list and the output will come out in order list and in range? For example the number enter is 2,5,1,4,6,3,8 then the result is number less than 5 are 1,2,3,4 and number less than 10 are 5,6,8

  • Haile Hadaro

    Thank U!

    • http://crunchify.com/ App Shah

      You are welcome.

  • Rabia

    there is another and shorter way of doing this program.

    public class JavaApplication11 {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            Scanner input=new Scanner(System.in);
           System.out.print("enter n");
           int n=input.nextInt();
           int count=1;
            int c=1,b=1,a=0;
           while(count<=n){
          
               c=b+a;
          System.out.print(c);
           a=b;
           b=c;
            
           count++;}
            }
        }
    
    • http://crunchify.com App Shah

      Thanks for posting. Just Print Number 1 Before while loop and you are all set.

    • Dixus

      check this out:
      class F{public static void main(String[] a){int f=0; int t=1;while(f<Long.parseLong(a[0])){System.out.println(f);t=f+(f=t);}}}

      fibonacci in 127 characters :D

    • asdf

      also change:”System.out.print(c);”

      to:”System.out.print(c + “,”);”

  • Tracy

    Thanks for explaining this…one question though, why is i=3 in the for statement of the Loop program?

    • http://crunchify.com App Shah

      Because 1st two digits are number 1.

      if(number == 1 || number == 2){
                  return 1;
              }
      
      • JackHCrow

        Or at least our purpose is to force the code to stick to our series, right? I tried it with int i = 1; within the loop, and it gave this output in case of up to 10:
        1 1 5 8 13 21 34 55 89 144

        in case of int i = 2; in the loop the output is:
        1 1 3 5 8 13 21 34 55 89

        Quite peculiar! That magical 2 was missing, yet it kept working with the rest of the series.

    • JackHCrow

      I would recommend you to run a Debug on this to understand how it works, by following my instructions using Eclipse: Place a Breakpoint to the first loop beneath the comment “//printing Fibonacci series upto number”, then to the Java loop solution parts to your “if” condition, and to its loop, then press Debug, and click okay to enter its perspective. Hit F6 to go step by step and take a look at the variables there while Eclipse debugging will highlight the parts green what is about to begin.

      Keep in mind that the loop you pointed at, is only looping a formula for exactly ONE digit result and giving it back to fibonacciLoop’s parameter as an output. Our main loop is the one that commands the function to guide through to the very last result, and that sub-loop will iterate until the main loop is done.

      My personal experience is this: If you give int i=1; within the loop condition, then it will count from 1 to 3 rather than counting from an initial 3, and adding the results to your fibonacci variable, so after the two digits of our output you will get 5 instead of 2 and then 3

  • Dark

    thanks for sharing. What environment it is? looks colorful and attractive :D

    • http://crunchify.com/ App Shah

      It’s syntax highlighter plugin.

  • HHHProgram

    Hey App Shah,
    Excellent article for the Fibonacci series of course this blog is doing a very good job of serving useful information. I’m proud to be a part of its Readers community.
    For the Fibonacci programs in different languange like C language,JAVA,C# must visit hhhprogram

    • http://crunchify.com/ App Shah

      Thanks much for your comment.