Fibonacci Series Program in Java
In this tutorial, we are going to see how to calculate the Fibonacci sequence using the “for” loop as well as recursion.
The Fibonacci series is a sequence of integers of 0, 1, 1, 2, 3, 5, 8….
The first two terms are 0 and 1. All other terms are achieved by adding the two previous terms. This means that the nth term is the sum of the (n-1)th and (n-2)th term.
Fibonacci series using the “for” loop
public class FibonacciMethod1{ public static void main(String args[]) { int nbr1=0, nbr2=1, nbr3, i, count=10; //print 0 and 1 System.out.print(nbr1+" "+nbr2); //The loop starts with 2 because 0 and 1 are already displayed for(i=2; i<count; ++i) { nbr3 = nbr1 + nbr2; nbr1 = nbr2; nbr2 = nbr3; System.out.print(" "+nbr3); } } }
Output:
0 1 1 2 3 5 8 13 21 34
Time complexity: O(n).
Space complexity: O(1).
Fibonacci series using recursion
public class FibonacciMethod2{ static int nbr1=0; static int nbr2=1; static int nbr3=0; static void displayFibonacci(int c){ if(c > 0){ nbr3 = nbr1 + nbr2; nbr1 = nbr2; nbr2 = nbr3; System.out.print(" "+nbr3); displayFibonacci(c-1); } } public static void main(String args[]){ int c = 10; //print 0 and 1 System.out.print(nbr1+" "+nbr2); //deduct 2 because 0 and 1 are already displayed displayFibonacci(c-2); } }
Output:
0 1 1 2 3 5 8 13 21 34
Time complexity: O(2^n).
Space complexity: O(n).