Back to: Java Tutorials

The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding numbers. In Java, we can generate the Fibonacci sequence using a recursive function or an iterative loop.

##### Recursive Function:

Here is an example of Java code to generate the Fibonacci sequence up to a given number `n`

:

```
public class Fibonacci {
public static void main(String[] args) {
int n = 10;
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n-1) + fibonacci(n-2);
}
}
```

In this code, the `main`

function initializes the variable `n`

to 10 and then uses a for loop to generate the Fibonacci sequence up to `n`

. For each iteration of the loop, the `fibonacci`

function is called with the current index as input, and the result is printed to the console.

The `fibonacci`

function takes an integer `n`

as input and returns the nth number in the Fibonacci sequence. The function uses recursion to calculate the Fibonacci number. The base case of the recursion is when `n`

is less than or equal to 1, in which case the function returns `n`

. Otherwise, the function calls itself with `n-1`

and `n-2`

as inputs, and returns the sum of the two calls.

When this code is executed, it will output the first 10 numbers in the Fibonacci sequence: `0 1 1 2 3 5 8 13 21 34`

.

##### Iterative Loop:

Here is an example of Java code to generate the Fibonacci sequence up to a given number `n`

using iteration:

```
public class Fibonacci {
public static void main(String[] args) {
int n = 10;
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if (n <= 1) {
return n;
}
int fib = 1, prevFib = 1;
for (int i = 2; i < n; i++) {
int temp = fib;
fib += prevFib;
prevFib = temp;
}
return fib;
}
}
```

In this code, the `main`

function initializes the variable `n`

to 10 and then uses a for loop to generate the Fibonacci sequence up to `n`

. For each iteration of the loop, the `fibonacci`

function is called with the current index as input, and the result is printed to the console.

The `fibonacci`

function takes an integer `n`

as input and returns the nth number in the Fibonacci sequence. The function uses an iterative loop to calculate the Fibonacci number. The loop starts at 2 and iterates until `n`

, at each iteration it calculates the next number in the sequence by adding the previous two numbers. The function returns the final number in the sequence.

When this code is executed, it will output the first 10 numbers in the Fibonacci sequence: `0 1 1 2 3 5 8 13 21 34`

.

Follow us on social media

Follow Author