Fibonacci Series in Java

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr

This is one of the articles from our Java Tutorial for Beginners.


Your Task:

Display the first 11 numbers of the Fibonacci sequence in the console.

A friendly reminder:

  • The first and second numbers in the Fibonacci sequence are 1.
  • And every following number is the sum of the two previous numbers.

This means that the numbers of the Fibonacci sequence are: 1 1 2 3 5 8 13 21 34 55 89 etc.

Solution:

If you run this code on your computer, you will see the following in your console:

1 1 2 3 5 8 13 21 34 55 89

Commentary:

We created 3 variables:

  • We assigned the value "1" to the first 2 variables, because the first number (n0) and the second number (n1) of the Fibonacci sequence are both 1.
  • We created a third variable and we called it n2.

And then we display the first two numbers of the Fibonacci sequence with the help of System.out.print(). To display these 2 numbers in a row, we used System.out.print() and not System.out.println().

To get the sum of the two previous numbers in the Fibonacci sequence, we use the "for" loop. And since we only need to display the first 11 numbers of the Fibonacci sequence, we write i<=11 as the condition of the "for" loop.

And then we write the following to display the numbers in the console:

You can find more articles in our Java Tutorial for Beginners.

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr
Самоучители--узнать детальнее--