×

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

Merge Sort in Java

Merge Sort in Java Merge sort in Java uses the divide and conquer approach to sort the given array/ list. There are three steps involved in the merge sort. 1) Divide the...

5 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

3 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

How to Convert long to String in Java

How to Convert long to String in java It is used if we have to display a long number in the text field because everything is displayed as a String. A...

3 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Java Macros

Macros are additions to the JDK 7 compiler in Java. Compile time macros are added and supported. Macros are Java classes that are instantiated and executed during the compilation process....

2 minutes read.

Java vs DotNET

Before understanding the differences between DotNET and Java, one must know about Java and DotNET. Java Java is a general-purpose programming language that is class-based and object-oriented, with minimal implementation dependencies. Regardless of...

9 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Getting Synchronized Set from Java HashSet

The synchronizedSet() technique for java.util.Collections class is utilized to return a synchronized (string safe) set supported by the predetermined set. To ensure sequential access, it is important that everything admittance...

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.

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.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.

Ternary Operator in Java

In some cases, the if...else expression in Java can be replaced by a ternary operator. Visit the Java if...else statement first before learning about the ternary operator. Ternary operator in Java A...

3 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

What is the ambiguity problem in Java?

The ambiguity problem in Java occurs when a method or constructor is overloaded with two or more methods with the same name but different parameters. This can confuse when multiple...

6 minutes read.