The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. So the sequence goes 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. Here’s how you can implement the Fibonacci sequence in Java:
public class Fibonacci { public static void main(String[] args) { int n = 10; // The number of Fibonacci numbers to generate int[] fib = new int[n]; // Array to store the Fibonacci numbers // Generate the first two Fibonacci numbers fib[0] = 0; fib[1] = 1; // Generate the rest of the Fibonacci numbers for (int i = 2; i < n; i++) { fib[i] = fib[i-1] + fib[i-2]; } // Print out the Fibonacci sequence for (int i = 0; i < n; i++) { System.out.print(fib[i] + " "); } } }
In the above code, we first declare the number of Fibonacci numbers we want to generate (in this case, 10). We then create an integer array fib
to store the Fibonacci numbers.
We generate the first two Fibonacci numbers (0
and 1
) and store them in the fib
array. We then use a for
loop to generate the rest of the Fibonacci numbers by adding the two preceding numbers in the sequence. We store each new Fibonacci number in the fib
array.
Finally, we use another for
loop to print out the Fibonacci sequence. The output of this program would be:
0 1 1 2 3 5 8 13 21 34