Today we are going to learn fibonacci series in java.

#### Fibonacci series in java

A fibonacci series is a sequence where each number is sum of previous two numbers.

Let’s see fibonacci sequence java using for loop,

// fibonacci java public class FibonacciDemo { public static void main(String[] args) { int num = 12, first = 0, second = 1; System.out.print("First " + num + " series : "); for(int a = 1; a <= num; ++a) { System.out.print(first + " , "); int total = first + second; first = second; second = total; } } }

**Output:**

First 12 series : 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89

In the same way we can use while loop in fibonacci series program,

// java fibonacci public class FibonacciExample { public static void main(String args[]) { int a = 1, num = 15, first = 0, second = 1; System.out.print("First " + num + " series : "); while(a <= num) { System.out.print(first + " , "); int total = first + second; first = second; second = total; a++; } } }

**Output:**

First 15 series : 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144 , 233 , 377

Similarly here’s the fibonacci recursive or java program using recursion,

// fibonacci series public class FibonacciRecursion { static intnum1= 0,num2= 1,num3= 0; static void fibonacciRecursive(int count) { if(count > 0) {num3=num1+num2;num1=num2;num2=num3; System.out.print(" " +num3); // fibonacci recursionfibonacciRecursive(count - 1); } } public static void main(String[] args) { int number = 12; System.out.print(num1+ " " +num2);fibonacciRecursive(number - 2); } }

**Output:**

0 1 1 2 3 5 8 13 21 34 55 89

Also read – transpose of a matrix