×

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion

Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1. Thus, we will get the series as 0, 1, 1, 2, 3, 5, 8, …...

We get the third term as 1 because its previous two terms are 0 and 1. The fourth term is 2 because its previous two terms are 1 and 1 and so on. Again, we will be discussing both the iterative as well as the recursive approach. Let us start with the iterative one.

Iterative Approach

Filename: FibonacciExample.java

public class FibonacciExample
{             
public static void main(String[] args)
{
// a and b will always contain the last two terms
// c will always contain the next term
int a = 0, b = 1, c; 
int n = 6; //We are calculating the series till the 6th term.  
System.out.println("The first " + n + " terms of the Fibonacci series are:");
for(int j = 0; j < n; j++)
{
               if (j == 0)
                              System.out.print(a + " ");
               else if( j == 1)
                               System.out.print(b + " ");
               else
                               {
                                              //calculating next term
                                              c = a + b;
                                              System.out.print(c + " ");
                                              //Updating the last two terms
                                              a = b;
                                              b = c;
                               }
}
}
}

Output:

The first 6 terms of the Fibonacci series are:
0 1 1 2 3 5

Explanation: The above approach is quite easy. First, we are initializing the first two terms of the series (a = 0 and b = 1). In the first two iterations, we are printing the first two terms. From the third iteration onwards, we are calculating the next term, printing it, and then updating the last two terms to get prepared for the next iteration. Now, let us discuss the recursive approach.

Recursive Approach

Filename: FibonacciExample1.java

public class FibonacciExample1
{
static int findFibonacci(int n)
{
               if(n <= 1) return n;
               // recursively calling to find and add last two terms
               return findFibonacci(n-1) + findFibonacci(n-2);
}
public static void main(String[] args)
{             
               int n = 6; //We are calculating the series till the 6th term. 
               System.out.println("The first " + n + " terms of the Fibonacci series are:");
for(int i = 0; i < 6; i++)
{
               int no = findFibonacci(i);
               System.out.print(no + " ");
}
}
}

Output:

The first 6 terms of the Fibonacci series are:
0 1 1 2 3 5

Explanation: We have seen that every term in the Fibonacci series is dependent on last two terms. Thus, if we define a function F(n) which gives the value of the nth term of the series, we get our recursion relation as:

F(n) = F(n-1) + F(n-2)

On the basis of the above relation, we have written our recursion method findFibonacci(). The if condition in the findFibonacci() method takes care of the base case: first term = 0 and second term = 1. Thus, we have:

findFibonacci(0) = 0

findFibonacci(1) = 1

findFibonacci(2) = findFibonacci(0) + findFibonacci(1) = 0 + 1 = 1

findFibonacci(3) = findFibonacci(2) + findFibonacci(1) = 1 + 1 = 2

findFibonacci(4) = findFibonacci(3) + findFibonacci(3) = 2 + 1 = 3

findFibonacci(5) = findFibonacci(4) + findFibonacci(3) = 3 + 2 = 5

Displaying Fibonacci Series Up to A Given Number

So far, we have only discussed to display the Fibonacci series up to given term (up to 6th term in our examples). However, we can also display the series up to a given number. The following example illustrates the same.

Filename: FibonacciExample2.java

public class FibonacciExample2
{
public static void main(String[] args)
{
// a and b will always contain the last two terms
// c will always contain the next term
int a = 0, b = 1, c; 
int n = 50; //We are calculating the series up to number n.  
System.out.println("The Fibonacci series up to the number " + n + " are:");
while(a <= n) // Restricting the display upto n
{
               System.out.print(a + " ");
               c = a + b; //finding next term
               //Updating last two terms
               a = b;
               b = c;
}
}
}

Output:

The Fibonacci series up to the number 50 are:
0 1 1 2 3 5 8 13 21 34

Explanation: Here, we limited our display up to number 50 by checking the last term is less than or equal to 50 or not in the while loop.


Related Topics

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

How to calculate time difference in Java

In this tutorial, we learned about how to calculate time differences in java language and which methods use to find the difference and its example. Prerequisite To understand this example, you need...

5 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Palindrome number program in Java

Write java program to check if a number is palindrome in Java? A number that does not change on reversing is called a palindrome number. In other words, when reversing the...

3 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

Automorphic Number Program in Java

We will learn about automorphic numbers through examples in this article, and we'll also make Java programmes that can determine whether a specific number was automorphic or not. What is an...

3 minutes read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.

Java throw

Java throw Sometimes it is required in the code to throw an exception deliberately. In order to achieve the same, the Java throw keyword should be used. One can throw either...

3 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

Modules in Golang

Modules are a way to manage dependency versions and enable reproducible builds of Go programs. They were introduced in Go 1.11 and are now the recommended way to manage dependencies...

4 minutes read.

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

22 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.

XOR of Array Elements Except Itself in Java

A lot of the biggest IT organisations, including The Google, Amazon, TCS, and The Accenture, etc., question about this issue in their interview processes. By addressing the issue, one hopes to assess...

5 minutes read.

Java Boolean logicalXor() Method

The logicalXor() method of Java Boolean class returns the result of implementing logical XOR operation on the specified Boolean operands. Syntax: public static boolean logicalXor (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.