Fibonacci Series in Java 

The Fibonacci series is a set of numbers where each number is the product of the two numbers before it. In the blog, we will explore more about the Fibonacci Series in Java.

How to Print Fibonacci Series in Java Program

Check how to print Fibonacci Series in Java mentioned as follows:

public class FibonacciSeries {
   public static void main(String[] args) {
      int a = 0, b = 1, c, count = 9;
      System.out.print(a + " " + b);

      for (int i = 2; i < count; i++) {
         c = a + b;
         System.out.print(" " + c);
         a = b;
         b = c;
      }
   }
}

Output:

0 1 1 2 3 5 8 13 21 

What is the Fibonacci Series?

The sum of the two numbers before it determines the value of each number in the Fibonacci series, a mathematical collection of numbers. Starting with 0 and 1, the Fibonacci series is never-ending. An Italian mathematician named Leonardo Fibonacci introduced the Fibonacci series in his book titled ‘Liber Abaci’ to the West. Common representations of the series include 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so forth. The series is applicable in a number of fields, including finance and computer science.

Methods to Create a Program in Java to Generate a Fibonacci Series

There are several variations to create a Fibonacci Series in Java and in this Blog, we have focused on demonstrating how to display the Fibonacci series in Java using for loop and while loop, Though  below are a list of some other variations for your knowledge:

A. Explain how to display the Fibonacci series using while loop

To better understand this concept of displaying the Fibonacci series in Java using a while loop, here’s an example:

public class Fibonacci {
    public static void main(String[] args) {
        int a = 0, b = 1, count = 9;
        System.out.print("Fibonacci Series of " + count + " numbers: ");

        while (count > 0) {
            System.out.print(a + " ");
            int sum = a + b;
            a = b;
            b = sum;
            count--;
        }
    }
}

Explanation of the code:

This code declares three variables: ‘a’, ‘b’, and ‘count’. The first and second numbers of the Fibonacci series, zero and one, are held respectively in the variables “a” and “b”. The variable “count” specifies the number of series numbers to be printed. This example prints the first nine digits of the Fibonacci series.

We first check if the “count” is greater than zero before starting the while loop. Then, we print the value of “a” inside the loop using the System.out.print method. We obtain the next number in the series by adding “a” and “b” and save the result in a variable called “sum”. Then set “a” equal to “b” and “b” equal to “sum” to update the variables for the next iteration.

We finally decrement the count variable by 1 to ensure that we do not print more numbers than intended.

Output:

If you execute the code above, the following output ought to appear:

Fibonacci Series of 9 numbers : 0 1 1 2 3 5 8 13 21 

 This is the first 9 numbers of the Fibonacci series starting from 0 and 1.

B. Explain how to  display Fibonacci series using for loop

To display the Fibonacci series using a for loop in Java, we can initialize the first two terms of the series to 0 and 1, respectively, and then use a for loop to calculate the subsequent terms. Inside the loop, we can print the current term of the series using the System.out.print method. Here’s an example code snippet that demonstrates how to display the first 10 terms of the Fibonacci series using a for loop:

public class Fibonacci {
    public static void main(String[] args) {
        int a = 9, b = 0, c = 1;

        System.out.print("Fibonacci Series of " + a + " numbers:");

        for (int q = 1; q <= a; ++q) {
            System.out.print(b + " ");

            int sum = b + c;
            b = c;
            c = sum;
        }
    }
}

Explanation of the code:

In this example, we have initialized the variables a, b, and c. Variable a specifies the number of terms to display, and b and c are the first two terms of the series.

We print the message “Fibonacci Series of ” + a + ” numbers:” to indicate that we are generating the Fibonacci series and the number of terms that will be printed.

Inside the for loop, we print the current value of b using System.out.print(b + ” “), and then calculate the next term of the series by adding b and c and storing the result in the variable sum. We then update the values of b and c to generate the next term of the series.

Finally, we close the for loop by incrementing the value of q by 1, and the loop will continue until q becomes greater than a.

Output:

Fibonacci Series of 9 numbers : 0 1 1 2 3 5 8 13 21 

C. Fibonacci series in Java series without use of recursion function

public class Fibonacci {
    public static void main(String[] args) {
        int a = 9;
    
        for (int i = 0; i < a; i++) {
            System.out.print(fibonacci(i) + " ");
        }
    }

    public static int fibonacci(int a) {
        if (a <= 1) {
            return a;
        }
        return fibonacci(a-1) + fibonacci(a-2);
    }
}

Explanation of the code:

The code works by first initializing n1 and n2 to 0 and 1, respectively. It then prints these two numbers, since they are the first two numbers in the Fibonacci series.

The for loop then iterates from i = 2 to i = n-1, where n is the number of terms we want to print. In each iteration of the loop, we calculate the next number in the Fibonacci series by adding n1 and n2. We print this number using System.out.print(sum + ” “);.

Finally, we update n1 and n2 to the next two numbers in the series by setting n1 equal to n2 and n2 equal to sum.

Output:

The output shows that the code correctly calculates and prints the first 9 numbers in the Fibonacci series.

0 1 1 2 3 5 8 13 21

D.  Fibonacci series in Java series with the use of recursive function

Check out an example of how to print the Fibonacci series in Java using a recursive function:

public class Fibonacci {
   public static void main(String[] args) {
        int a = 9;
    
        for (int i = 0; i < a; i++) {
          System.out.print(fibonacci(i) + " ");
        }
    }

    public static int fibonacci(int a) {
        if (a <= 1) {
            return a;
        }
        return fibonacci(a-1) + fibonacci(a-2);
    }
}

Explanation of the code:

This code correctly prints the first numbers in the Fibonacci series using recursion. Lets see how it works:

The main method initializes the variable a to 9, which specifies that we want to print the first 9 numbers in the Fibonacci series.

Next, the for loop iterates from 0 to 8 (since i starts at 0 and stops before reaching a), and for each iteration, it calls the Fibonacci method and prints the result.

The Fibonacci method is a recursive function that calculates the ath number in the Fibonacci series. If a is 0 or 1, the function returns a (since the 0th and 1st numbers in the series are both equal to their own values). Otherwise, the function recursively calls itself with a-1 and a-2, and adds the results together to get the ath number in the series.

Output:

When we run this code, it will output the first 9 numbers in the Fibonacci series, which are:

0 1 1 2 3 5 8 13 21

E. Describe how to use if/else statement

To use the Fibonacci series in Java with an if/else statement, you can write a program that asks the user for a number n and then prints the first n numbers of the Fibonacci sequence.

import java.util.*;       // wildcard Scanner import

public class FibonacciSeries {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number of terms in the Fibonacci sequence: ");
        int a = input.nextInt();
        
        int p = 0;
        int q = 1;
        int r = 0;
        
        if(a == 1) {
            System.out.print(p);
        }
        else if(a == 2) {
            System.out.print(p + " " + q);
        }
        else {
            System.out.print(p + " " + q);
            for(int i = 3; i <= a; i++) {
                r = p + q;
                System.out.print(" " + r);
                p = q;
                q = r;
            }
        }
    }
}

Explanation of the code:

We start by importing the Scanner class from java.util package to get user input.

Then we prompt the user to enter the number of terms in the Fibonacci sequence they want to see.

We declare and initialize three integer variables p, q, and r. We use p and q to keep track of the previous two terms in the sequence, and we use r to calculate the next term in the sequence.

The if/else statement checks if a is equal to 1 or 2, and prints the appropriate number of terms.

If a is greater than 2, we use a for loop to calculate and print the remaining terms of the Fibonacci sequence. In each iteration of the loop, we calculate the value of r by adding p and q, and print it out. Then, we update the values of p and q to move to the next pair of terms in the sequence.

Output:

Finally, the program prints the Fibonacci sequence up to the nth term specified by the user.

Enter the number of terms in the Fibonacci sequence: 7
0 1 1 2 3 5 8

F. Explain how to display the Fibonacci series up to give number

To display the Fibonacci series up to a given number n in Java, you can use a while loop or a for loop. Below is an example of how to display the Fibonacci series in Java up to give a number:

import java.util.*;       // wildcard Scanner import
public class FibonacciSeries {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number to display the Fibonacci series up to: ");
        int n = input.nextInt();
        
        int k = 0;
        int l = 1;
        int m;
        
        System.out.print("  " + k + "  " + l + "  "); // print the first two terms
        
        while (k + l <= n) { // keep going until the sum of k and l exceeds n
            m = k + l;
            System.out.print(" " + m + " ");
            k = l;
            l = m;
        }
    }
}

Explanation of the code:

Prompt the user to enter a number ‘n’ to display the Fibonacci series up to. Initialize the variables ‘k’ and ‘l’ to 0 and 1 respectively, representing the first two terms of the Fibonacci series.

Declare the variable ‘m’ to hold the sum of ‘k’ and ‘l’.Print the first two terms of the series using the ‘System.out.print’ statement. Run the ‘while’ loop until the sum of ‘k’ and ‘l’ exceeds the given number ‘n’.

Calculate the variable ‘m’ as the sum of ‘k’ and ‘l’ inside the loop, and print it. Update the values of ‘l’ and ‘k’ by assigning ‘l’ to ‘k’ and ‘m’ to ‘l’, respectively, to move on to the next term in the series. This is done to move on to the next term in the series. Continue the loop until the sum of the last two printed terms is greater than ‘n’, and terminate it at that point.

Output:

If the user enters ’20’ as the input, the output will be:

Enter a number to display the Fibonacci series up to: 20
0 1 1 2 3 5 8 13

In this example, the user enters the number 20. The program prints the first two terms of the Fibonacci series (0 and 1), then continues the loop until the sum of the previous two terms is greater than 20. The resulting series printed by the program is 0 1 1 2 3 5 8 13, which is the Fibonacci series up to the number 20.

Why is the Fibonacci Series important?

There are several reasons why the Fibonacci series is important:

  • Mathematics: Mathematicians describe the Fibonacci series as a series of numbers, where each number results from adding the two previous numbers.
  • Computer Science: Computer scientists use the Fibonacci series, especially in algorithms and data structures like the Fibonacci heap.
  • Nature: Biologists, botanists, and other natural scientists use the Fibonacci sequence to understand how leaves arrange on stems, trees branch out, and seashells grow.
  • Finance:  Traders and investors use the Fibonacci sequence for predicting price changes and identifying potential areas of support and resistance.

Overall, Multiple fields of study use the Fibonacci series, making it a vital mathematical concept and an exciting topic for investigation and study.

In conclusion, let us say that the Fibonacci series is an intriguing collection of numbers that has captivated mathematicians for centuries. It is described as a series of numbers, where each number is the result of the two previous numbers. We can quickly generate the Fibonacci series in Java by using loops or recursion.

The Fibonacci series is a mathematical idea that has real-world applications in many fields, such as science, engineering, and finance. It can be seen in patterns in nature, such as leaves on a stem, tree branching, and snail shell spirals.

We hope that our blog post on “Fibonacci Series in Java” will effectively guide and inform you about your Java-related queries. To keep enhancing your coding skills, do check out Newtum’s website and explore our online coding courses covering Java,Python, PHP, and more.

FAQ 

1. What is the importance of the Fibonacci Series in mathematics?

Answer: The Fibonacci Series is a fundamental mathematical sequence where each number is the sum of the two preceding ones. It has applications in various mathematical concepts, including number theory, combinatorics, and algebra.

2. How can I generate a Fibonacci Series in Java using a while loop?

Answer: To generate a Fibonacci Series using a while loop in Java, you can start with two initial values (0 and 1) and use a loop to calculate and print the subsequent numbers in the series by adding the two previous ones.

3. Why is the Fibonacci Series important in computer science and programming?

Answer: Computer scientists and programmers use the Fibonacci Series in various algorithms and data structures. One prominent example is the Fibonacci heap, which is used in priority queue implementations and graph algorithms.

4. Can I calculate Fibonacci numbers in Java without using recursion?

Answer: Yes, you can calculate Fibonacci numbers in Java without using recursion. One common approach is to use a loop (e.g., a for loop or a while loop) to generate the series iteratively without the need for recursive function calls.

5. How is the Fibonacci Series applied in finance and trading?

Answer: In finance, traders and investors use the Fibonacci Series for technical analysis. It helps identify potential levels of support and resistance in stock prices and other financial instruments, aiding in making informed trading decisions.

About The Author