How to calculate Fibonacci iteratively in Java

In a Fibonacci sequence, a number is generated by adding previous two numbers, with first two numbers as 0 and 1. Thus, a[i] is calculated as a sum of a[i-1] and a[i-2]. Below is the code fragment to generate Fibonacci Sequence in Java, iteratively:

Output of above code fragment would be:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Please let us know if there are better way of doing the things.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">