Fibonacci Series in Java

In this tutorial, we will calculate Fibonacci numbers in 3 seperate ways including for loop, do-while loop and arrays. And also we will create a program to find nth Fibonacci number with user input

Fibonacci Series in Java

Also Excel Solution: Calculating Fibonacci Series in Microsoft Excel

Solution 1: Just adding and printing Fibonacci numbers in for array:

public class fibonacciNumbers1{

	public static void main(String[] args) {
		
		int num1, num2;
		num1=1;
		num2=1;
	    System.out.print(num1+" "+num2+" ");
	    
		for (int i=1; i<=10; i++) {
			num1+=num2;
		    System.out.print(num1+" ");
		    num2+=num1;
		    System.out.print(num2+" ");
		}
		//1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 
	}

}

Solution 2: Just adding and printing Fibonacci numbers in do-while array:

public class fibonacciNumbers2{

	public static void main(String[] args) {
		
		int num1=1, num2=1;
	    
	    do
	    {
	    	System.out.print(num1+" "+num2+" ");
	    	num1+=num2;
		    num2+=num1;
	    }
	    while(num1<20000);

		//1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711  
	}

}

Solution 3: Keeping Fibonacci values in array (first 25 Fibonacci numbers)

public class maxmin {

	public static void main(String[] args) {
		int[] fibonacciArray = new int[25];
		fibonacciArray[0]=1;
		fibonacciArray[1]=1;
	    
		//calculating fibonacci numbers
	    for (int i=2; i<fibonacciArray.length; i++)
	    {
	    	fibonacciArray[i] = fibonacciArray[i-1] + fibonacciArray[i-2];
	    }
	    
	    //printing fibonacciArray values
	    for (int i=0; i<fibonacciArray.length; i++)
	    {
	    	System.out.print(fibonacciArray[i]+" ");
	    }
	    //1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 
	}

}

Bonus: Finding nth Fibonacci number

import java.util.Scanner;

public class maxmin {

	public static void main(String[] args) {
		
		Scanner input = new Scanner(System.in);
		
		int[] fibonacciArray = new int[25];
		fibonacciArray[0]=1;
		fibonacciArray[1]=1;
	    
		//calculating fibonacci numbers
	    for (int i=2; i<fibonacciArray.length; i++)
	    {
	    	fibonacciArray[i] = fibonacciArray[i-1] + fibonacciArray[i-2];
	    }
	    
	    System.out.println("What is n?");
	    int n=input.nextInt();
	    
	    System.out.println(n+"th Fibonacci number is:"+fibonacciArray[n-1]);
	}

}

Output:

What is n?
> 8
8th Fibonacci number is:21