Implementing the Fibonacci Sequence in Java
To implement the Fibonacci sequence in Java, we can use an iterative approach. The iterative approach involves using a loop to calculate each Fibonacci number in the sequence.
Here's an example implementation of the Fibonacci sequence in Java:
public class FibonacciSequence {
public static int getFibonacciNumber(int n) {
if (n <= 1) {
return n;
}
int a = 0, b = 1, c;
for (int i = 2; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
public static void main(String[] args) {
System.out.println("Fibonacci sequence up to the 10th number:");
for (int i = 0; i < 10; i++) {
System.out.print(getFibonacciNumber(i) + " ");
}
}
}
The getFibonacciNumber()
method takes an integer n
as input and returns the n
th Fibonacci number. The method first checks if n
is 0 or 1, in which case it returns n
directly. For all other cases, it uses a loop to calculate the Fibonacci numbers up to the n
th number.
The output of the above code will be:
Fibonacci sequence up to the 10th number:
0 1 1 2 3 5 8 13 21 34
The time complexity of this iterative implementation is O(n), as it calculates each Fibonacci number sequentially.
In the next section, we will explore some applications of the Fibonacci sequence.