Table of Contents
Toggle7 Methods to Write Fibonacci Series Program in Java
Fibonacci numbers are one of math and science’s favorite numbers. You might find it strange that there are some fixed numbers that we can see everywhere, like in science, math, the arts, etc. The series of these numbers is called the Fibonacci series. This series starts with 0 and 1. In this blog post, we will explore the top 7 Methods to Write Fibonacci Series Program in Java
- for loop
- while loop
- scanner
- recursion
- function
- Memoization
- Implement an Efficient O(log n) Fibonacci Generator
What is the Fibonacci series?
Leonardo Fibonacci, an Italian Mathematician, gave this Fibonacci sequence in his book “Libre Abachi“. Even some of the Sanskrit texts mention this sequence. You can even find this sequence in the flowers.
The Fibonacci series is a sequence of numbers that starts with 0 and 1. The next two digits are added together.
What does this mean?
Suppose I have taken two numbers initially, let’s say 0 and 1. Fibonacci numbers begin with these two. These two numbers, 0 and 1, when added together, produce the next Fibonacci number –
0+1 = 1
Again, if you add 1+1, it will generate 2. Now it will follow this sequence.
1+2=3
2+3=5
5+3=8
And so on…
That’s how we get the Fibonacci series:- 0, 1, 1, 2, 3, 5, 8,…
There are now multiple approaches to writing a Fibonacci series program in Java. Following are the 7 methods that are most used for Fibonacci series program in Java –
- for loop
- while loop
- scanner
- recursion
- function
- Memoization
- Implement an Efficient O(log n) Fibonacci Generator
Ready to level up your skills in Core Java?
Enroll now for endless software development opportunities!
Fibonacci series program in Java using for loop
Input / Source Code:
The program uses a “for loop” to calculate and print the Fibonacci series.
We initialize two variables, “prev” and “curr”, with the first two numbers of the series, 0 and 1. These two variables will help us calculate the next numbers in the series.
The loop runs n times, where n is the number of terms we want in the series.
In each iteration of the loop, we print the value of “prev” (current Fibonacci number). Then calculate the next Fibonacci number by adding “prev” and “curr”. Finally, store it in the variable “next”.
We update “prev = curr”, and “curr = next” after that. We loop to the next Fibonacci number this way.
As a result, the program will print the Fibonacci series with the desired number of terms specified by the value of n.
Output:
Elevate your Java skills with our Advanced Java Course!unlock endless possibilities in software development.
Java Program to print Fibonacci series using while loop
Input / Source code:
In this program, you’re using the while loop.
You set two variables, ‘prev’ and ‘curr’, to 0 and 1. These variables will help you calculate the next numbers in the series.
Now, you start the while loop. As long as you haven’t printed all the 10 terms (i < n), you keep going. Inside the loop, you print the current number ‘prev’ because that’s the first number in the series.
Then, you calculate the next number by adding ‘prev’ and ‘curr’. You save it in a new variable called ‘next’. This way, you have the next number ready to print in the next iteration.
You update the prev and curr variables with the new values. Now, ‘prev’ becomes the same as the current number ‘curr’, and ‘curr’ becomes the next number you calculated (next). It’s like you are shifting to the next numbers in the series.
You also have a counter variable ‘i’ that keeps track of the number of terms you have printed so far. You increase it by 1 after each iteration.
The loop continues until you have printed all 10 terms (i becomes equal to n). The loop will stop when that happens.
Output:
Enroll now in our Java classes at Technogeeks CS, Pune, and unlock your coding potential for a successful career!
Fibonacci series program in Java using scanner
Input / Source Code:
In this program, we prompt the user to enter the number of terms they want in the Fibonacci series using the `Scanner` class. The entered value is stored in the variable `n`.
Then, we use a `for` loop to calculate and print the Fibonacci series. We initialize two variables, `prev` and `curr`, with the first two numbers of the series, 0 and 1.
In each iteration of the loop, we display the current Fibonacci number, add it to `curr, and store it in `next`. We then set `prev` to `curr` & `curr` to `next`. This way, we move to the next numbers in the Fibonacci series until we reach the desired number of terms specified by the user.
Output:
Ready to become a Full-Stack Java Developer?
Enroll now at Technogeeks CS to secure your future!
Fibonacci series program in Java using recursion
Input / Source code:
This program uses recursion, which is like a function calling itself to solve a problem.
Inside the `fibonacci` function, there’s a base case. A base case is like a stopping point. We’ve reached the first two Fibonacci series terms if ‘n’ is 0 or 1. In that case, the function simply returns `n` itself because these are the starting numbers.
Now, for `n` greater than 1, it gets interesting! The function needs to calculate the nth number in the series. But how? That’s where recursion comes in!
To calculate the nth number, the function calls itself twice! Once with `n-1` and once with `n-2`. These recursive calls continue until the function reaches the base case (n is 0 or 1). Then, the function starts to “unwind” the recursive calls and calculate the nth Fibonacci number by adding the results of the previous two numbers.
Now, back in the `main` method, you want to print the Fibonacci series. You use a `for` loop to go from 0 to `n-1` (since array indices start from 0). You call the `fibonacci` function and print the returned value for each `i` value. This way, you generate and print the first 10 numbers of the Fibonacci series.
Output:
Java program to print Fibonacci series using function
Input / Source code:
The `fibonacci` function is quite simple. We reached the first two numbers in the sequence if `n` is 0 or 1. In that case, the function directly returns `n` itself because these are the starting numbers.
For `n` greater than 1, it gets more interesting! The function uses a concept called recursion. It calls itself twice! Once with `n-1` and once with `n-2`. These recursive calls continue until we reach the base cases (n is 0 or 1).
How does this assist compute the nth Fibonacci number? Well, the magic happens when the recursive calls start to “unwind.” Once we reach the base cases, the function starts to calculate the nth Fibonacci number by summing the results of the previous two numbers.
We return to the main function after completing the fibonacci function. To generate the Fibonacci series, we use a loop. We pick a `for` loop and start iterating from 0 to `n-1` (since array indices start from 0).
This generates and prints the first 10 Fibonacci numbers.
Output:
Fibonacci Series in Java Using Memoization
Input / Source code:
To generate the series, we create a special function called `fibonacci`. This function calculates the nth Fibonacci number using recursion. Recursion is like a function calling itself to solve a problem.
Now, here’s the interesting part:- We use a technique called memoization to make the program faster and efficient.
Memoization means that we store the results of previously calculated Fibonacci numbers in a special place called a HashMap. The HashMap acts like a storage room where we keep the results of calculations for future use.
Before calculating the nth Fibonacci number, we first check if it’s already stored in the HashMap. If it is, we simply return that stored value. This way, we avoid redundant calculations for the same Fibonacci number, which can be time consuming.
We calculate it recursively if the Fibonacci number is not in the HashMap. The logic is the same as before: If `n` is 0 or 1, we directly return `n` itself because these are the starting numbers. For `n` greater than 1, we sum the results of the previous two Fibonacci numbers.
We store the nth Fibonacci number in the HashMap. Thus, we may recover the same Fibonacci number from the HashMap without recalculating it if required.
Finally, in the `main` function, we produce and publish the first 10 Fibonacci numbers using a `for` loop. The `fibonacci` function calculates the nth Fibonacci number for each `i` in the loop.
Memoization using recursion is helpful for solving issues like the Fibonacci sequence because it saves duplicate computations and speeds up the program.
Output:
Java Program to Implement Efficient O(log n) Fibonacci Generator
To implement an efficient O(log n) Fibonacci generator in Java, you can use matrix exponentiation. This technique calculates Fibonacci numbers in logarithmic stages using matrix multiplication and exponentiation.
Input / Source code:
This program relies on `fibonacci`. This method returns the nth Fibonacci number.
How is it so fast? It employs “matrix exponentiation.” It’s a smart approach to compute Fibonacci numbers in fewer steps.
The application initializes a specific 2×2 matrix to perform this. Then, `powerMatrix` increases this matrix to the power of (n – 1). This is the secret to effectively calculating Fibonacci numbers!
Magic occurs in powerMatrix. It’s recursive and employs “divide and conquer.” It speeds up calculations by dividing them.
The `multiplyMatrices` function multiplies matrices. Don’t worry! The application handles all matrix things.
After the `powerMatrix` function, the `matrix` retains the matrix exponentiation result and the nth Fibonacci number at `matrix[0][0]`!
Finally, the software prints, “The 10th Fibonacci number is: 55.”
This software calculates Fibonacci numbers rapidly, even for extremely large n. Matrix exponentiation generates Fibonacci numbers efficiently, making it a useful tool for mathematical problems and algorithms!
Output:
Enroll now in our Java classes at Technogeeks and unlock your coding potential for a successful career!
Limited spots available; act fast!