Fibonacci succession in Java

By kedinn 2014/03/02

We will see how the Fibonacci succession in Java works. In the Fibonacci the first elements are 0.1, for the following elements are obtained both adding of previous numbers, an example we can see: 0, 1, 1, 2, 3, 5, 8, 13, 21, 33, ........ and continuous one of the same form.

In the following example, we asked that the user enters a +positivo number that sera element. And soon it would show the results to us of the series.

public class Fibona \ {

public static void main (String [] args) \ {int element = 0; String result;

//So that the user enters a positive number. do \ {result = JOptionPane.showInputDialog (“Writes a positive number. \ n? + “To leave = -1?); element = Integer.parseInt (result);

} while (element < -1 && element! = -1);

//the variables for the numbers ant=anterior, act=actual and next+siguiente int ant = 0; int act = 1; int next = 1;

//Imprimimos the 0. System.out.print (“0,?); for (int i = 0; i < element - 1; i++) \ {System.out.print (next + “,?); //Extreme of the present one with the previous one to have siguietne element next = act + ant; ant = act; act = next; } System.out.println (); }}

It would show us in the screen when the user enters I number 6.

run:
0, 1, 1, 2, 3, 5, BUILD SUCCESSFUL (total Time: 5 seconds)