Java Program to Display Fibonacci Series
Display Fibonacci Series
The Fibonacci series is a series where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1.
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Suppose, our first two terms are:
first = 0 second = 1
The next terms in the Fibonacci series would be calculated as:
nextTerm = first + second; (0 + 1) first = second; (1) second = nextTerm; (1) nextTerm = first + second; (1 + 1)
Let's now apply this logic to our program.
Example: Display Fibonacci Series Using for Loop
class Main { public static void main(String[] args) { int n = 10, first = 0, second = 1; System.out.println("Fibonacci Series till " + n + " terms:"); for (int i = 1; i <= n; ++i) { System.out.print(first + ", "); // compute the next term int nextTerm = first + second; first = second; second = nextTerm; } } }
Output
Fibonacci Series till 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
In the above program, first and second are initialized with 0 and 1 respectively (first two digits of the Fibonacci series).
Here, we have used the for
loop to
- print the first of the series
- compute nextTerm by adding first and second
- assign value of second to first and nextTerm to second
Display the Fibonacci series up to a given number
class Fibonacci { public static void main(String[] args) { int n = 100, first = 0, second = 1; System.out.println("Fibonacci Series Upto " + n + ": "); while (first <= n) { System.out.print(first + ", "); int nextTerm = first + second; first = second; second = nextTerm; } } }
Output
Fibonacci Series Upto 100: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
In this example, instead of displaying the Fibonacci series of a certain number, we are displaying the series up to the given number (100).
For this, we just need to compare the first with n. And, if first is less than n, it is printed in the series. Else, the series is completed.
We can also use a while
loop to generate the Fibonacci series in Java.
Display the Fibonacci series using a while loop
class Main { public static void main(String[] args) { int i = 1, n = 10, first = 0, second = 1; System.out.println("Fibonacci Series till " + n + " terms:"); while (i <= n) { System.out.print(first + ", "); int nextTerm = first + second; first = second; second = nextTerm; i++; } } }
Output
Fibonacci Series till 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
The working of this program is the same as the previous program.
And, though both programs are technically correct, it is better to use a for
loop in this case. It's because the number of iterations (from 1 to n) is known.