Java Programs 13: Java Program to Print Fibonacci Series of Given Length Using Collection

Hello Folks,

This is a frequently asked programming interview question to print a fibonacci series of given length.

Fibonacci series:

Wikipedia defines it very well.

The Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones:

Often, especially in modern usage, the sequence is extended by one more initial term:

By definition, the first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.
So now we know what is fibonacci series. Let’s think of logic to convert in program:
• We need to store numbers in variables.  Since we need to store multiple variables of same type, instead of creating multiple variables, we can use an array or a collection class.
• In this post, I will use a collection class instead of arrays. In an interview if you solve a program using collections, it is really appreciated and leaves a positive impact on your interviewer.
• To find nth index  number in fibonacci series, you need to access and add (n-1)th index and (n-2)th indexed element.

Java program:

Output:

If you like my posts, please like, comment, share and subscribe.

#HappyCoding

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

2 thoughts on “Java Programs 13: Java Program to Print Fibonacci Series of Given Length Using Collection”

1. Uday Neavse says:

your code will break if user enter length of series in three digit

2. Very nice and different logic using collections. Thanks for sharing it. Generally everyone uses the simple one in case they want to print the first 10 numbers of Fibonacci series

a=0
b=1

print a
print b

while(counter < 8)
{
c=a+b
print c
a=b
b=c
}