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

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

with seed values

Here is a simplest Java Program to generate Fibonacci Series.

### Method-1 and Method-2 in a single program

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
package crunchify.com.tutorials; import java.util.Scanner; /** * @author Crunchify.com * */ public class CrunchifyFibonacci { @SuppressWarnings("resource") public static void main(String args[]) { // input to print Fibonacci series upto how many numbers log("Enter number upto which Fibonacci series to print: "); int number = new Scanner(System.in).nextInt(); log("\nUsing Method-1: Using Recursion. Provided Number: " + number); // printing Fibonacci series upto number for (int i = 1; i <= number; i++) { log(fibonacciRecusion(i) + " "); } log("\nMethod-2: Fibonacci number at location " + number + " is ==> " + (fibonacciLoop(number) + "")); } // Method-1: Java program for Fibonacci number using recursion. public static int fibonacciRecusion(int number) { if (number == 1 || number == 2) { return 1; } return fibonacciRecusion(number - 1) + fibonacciRecusion(number - 2); // tail recursion } // Method-2: Java program for Fibonacci number using Loop. public static int fibonacciLoop(int number) { if (number == 1 || number == 2) { return 1; } int fibo1 = 1, fibo2 = 1, fibonacci = 1; for (int i = 3; i <= number; i++) { fibonacci = fibo1 + fibo2; // Fibonacci number is sum of previous two Fibonacci number fibo1 = fibo2; fibo2 = fibonacci; } return fibonacci; // Fibonacci number } private static void log(String number) { System.out.println(number); } } |

#### Result of method-3 and method-4:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Enter number upto which Fibonacci series to print: 10 Using Method-1: Using Recursion. Provided Number: 10 1 1 2 3 5 8 13 21 34 55 Method-2: Fibonacci number at location 10 is ==> 55 |

### Method-3

Than you `S.Sur`

for posting code as a comment.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package crunchify.com.tutorials; import java.util.Scanner; public class CrunchifyFibonacciOption3 { public static void main(String args[]) { System.out.println("Enter the term to be printed"); Scanner ob = new Scanner(System.in); int ch = ob.nextInt(); System.out.println("The" + ch + " terms of fibanocci numbers are-"); int a, b, s, n; a = b = 1; for (n = 1; n <= ch; n++) { System.out.println(a); s = a + b; a = b; b = s; } } } |

#### Result of method-3

1 2 3 4 5 6 7 8 |
Enter the term to be printed 5 The5 terms of fibanocci numbers are- 1 1 2 3 5 |

### Method-4

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package crunchify.com.tutorials; import java.util.Scanner; public class CrunchifyFibonacciOption4 { public static void main(String args[]) { System.out.println("Enter the term to be printed"); Scanner ob = new Scanner(System.in); int a = 1; int b = 0; int ch = ob.nextInt(); ; for (int i = 0; i < ch; i++) { System.out.print(b); b = a + b; a = b - a; if (i <= ch - 2) { System.out.print(", "); } if (i == ch - 1) { System.out.println(".\nThese are the first " + ch + " Fibonacci Numbers!"); } } } } |

#### Result of method-4:

1 2 3 4 |
Enter the term to be printed 5 0, 1, 1, 2, 3. These are the first 5 Fibonacci Numbers! |

S.Sur says

i hope you will like my program

App Shah says

Thanks much S.Sur for providing another method to print fibonacci series. I’ve just added your code above for all Crunchify Readers.

Happy coding. Really appriciate your code.

S.Sur says

another way of doing it in a shorter manner (this is a compiled program) but thanks for your program too

Michael says

What would be the issue with this implementation? It seems like everyone else’s implementations are more complex; is there a reason why the below might have an issue?

App Shah says

Thanks Michael for your code too. I’ve added your code too into above tutorial.

bort123 says

And there’s always:

public int fibonacci(int n) {

return (n<=1)? n:fibonacci(n-1)+fibonacci(n-2);

}

App Shah says

Great. Thanks 🙂

Damey Dame says

I’m sorry if this is a useless question, but I am pretty new to programming.

What does the fibonacciLoop method do? I couldn’t work it out so I copied the code directly into eclipse and commented out that entire method and the program seems to run exactly the same.

What am I missing?

App Shah says

Hi Damey – fibonacciLoop() method will give you fibonacci number at given position. Yeah before it wasn’t even used in code. I’ve just updated code and result which invokes fibonacciLoop() method now. Kindly revisit above steps and let me know if you have any more questions.

Happy coding.

Aristides MH says

Hi I like this style, to avoid errors with negative numbers.

public static Integer getFibonacci(int x) {

if (x <= 0)

return 0;

if (x == 1)

return 1;

return getFibonacci(x – 1) + getFibonacci(x – 2);

}

Alok Naushad says

yeah no need to be this complex

Here

import java.util.Scanner;

class Fibonacci

{

public static void main(String args[])

{

System.out.println(“Enter the maximum no. of lines”);

Scanner ob=new Scanner(System.in);

int ch = ob.nextInt();

System.out.println(“Ther you go with the “+ch+” series of Fibanocci Numbers”);

int a, b, s, n;

a=b=1;

for(n=1;n<=ch;n++)

{

System.out.println(a);

s=a+b;

a=b;

b=s;

}

}

}

Aishwarya S says

the output which I got for the above program is

1 1 2 3 5 when I entered n as 5

but fibonacci series start with 0, right.

App Shah says

As per my information. 0 should not be considered as a Fibonacci number.

Michał Załęcki says

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

Aristides MH says

Hey, your method works fine but I suggest to change your type from long to BigInteger. when I test it with value 95 it return -4953053512429003327 also fail with 93, 97, 99, 105.

David Leonhartsberger says

I think the first recurisve implementation is not tail recusive

Redman says

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.

App Shah says

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

Redman says

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 says

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

App Shah says

Will update above code soon with that option.. 🙂

Smirnoff says

you don’t need a third variable

mrphi says

What is the plugin for source code ?

App Shah says

I’m using Crayon Syntax Highlighter.

Neel Sheyal says

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.

App Shah says

Thanks Neel. Could you share your code?

kaustab ganguly says

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

umika says

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 says

Thank U!

App Shah says

You are welcome.

Rabia says

there is another and shorter way of doing this program.

App Shah says

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

Dixus says

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 😀

asdf says

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

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

ProJava says

This doesn’t work looking at it

It first prints one which is right but then it prints 2 when it’s supposed to print 1 again

To fix this b should be 0

ProJava says

Nvm

bhavya says

you forgot to import java.util.scanner

Krushio Vida says

Add System.out.print(“0 1 “); at the top of the while…

Tracy says

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

App Shah says

Because 1st two digits are number 1.

JackHCrow says

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 says

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 says

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

App Shah says

It’s syntax highlighter plugin.

HHHProgram says

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

App Shah says

Thanks much for your comment.