Write Java Program to Print Fibonacci Series up-to N Number [4 different ways]

Last updated
App Shah
Crunchify » Java and J2EE Tutorials » Write Java Program to Print Fibonacci Series up-to N Number [4 different ways]
Write Java Program to Print Fibonacci Series up-to N Numbers

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

Fibonacci Series Example - crunchify.co

Here is a simplest Java Program to generate Fibonacci Series.

Method-1 and Method-2 in a single program

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:

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

Thank you S.Sur for posting code as a comment.

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

Enter the term to be printed
5
The5 terms of fibanocci numbers are-
1
1
2
3
5

Method-4

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:

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

46 thoughts on “Write Java Program to Print Fibonacci Series up-to N Number [4 different ways]”

  1. i hope you will like my program

    import java.util.Scanner;
    class fibonacci_series
      {
       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;
          }
        }
      }
    
    Reply
    • 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.

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

    import java.util.Scanner;
    class fibonacci_series
      {
       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;
          }
        }
      }
    
    Reply
    • 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?

      int a = 1;
              int b = 0;
              int loopEnd = 30;
              for (int i = 0; i < loopEnd; i++) {
                  System.out.print(b);
                  b = a + b;
                  a = b - a;
                  if (i <= loopEnd -2){
                      System.out.print(", ");
                  }
                  if (i == loopEnd -1){
                      System.out.println(".\nThese are the first " + loopEnd + " Fibonacci Numbers!");
                  }
              }
      Reply
  3. 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?

    Reply
    • 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.

      Reply
  4. 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);
    }

    Reply
  5. 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;
    }
    }
    }

    Reply
  6. 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;
    }
    Reply
    • 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.

      Reply
  7. 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.

    Reply
  8. 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.

    Reply
  9. 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

    Reply
  10. 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++;}
            }
        }
    Reply
      • 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.

        Reply
    • 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

      Reply
  11. 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

    Reply

Leave a Comment