Search Logic Blocks

Monday, October 19, 2020

Java: Let's Practice - How to create Fibonacci sequence through recursion

What is the Fibonacci sequence?
Fibonacci sequence is a sequence of numbers generating new number by adding two previous numbers. It starts with 0 and 1.

SequenceLast two nos.
0
1
10+1
21+1
31+2
52+3

0, 1, 1, 2, 3, 5, 8, 13.......

So, to create recursive method to get next number in the sequence, program should use the same method which calculates the previous numbers of the sequence -

fib(0) = 0
fib(1) = 1
fib(2) = fib(1) + fib(0)
fib(3) = fib(2) + fib(1)
........
fib(n) = fib(n-1) + fib(n-2)

Here is the code -
import java.util.Scanner;

public class FibonacciDemo {
static int[] fibnos;
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
int n = sc.nextInt();
fibnos = new int[n+1];
int fib = fibonacci(n);
System.out.println(n + "th number in the Fibonacci Sequence (0, 1, 2, ...) is : " + fib);

for(int i = 0; i < fibnos.length; i++) {
System.out.print(fibnos[i] + ", ");
}
}

public static int fibonacci(int n) {
int result = 0;

if(n == 0) {
fibnos[0] = 0;
return 0;
}
if(n == 1) {
fibnos[1] = 1;
return 1;
}
result = fibonacci(n-1) + fibonacci(n-2);
fibnos[n] = result;
return result;
}
}
And here is the output -

Enter the number: 6
6th number in the Fibonacci Sequence (0, 1, 2, ...) is : 8
0, 1, 1, 2, 3, 5, 8, 

And here is the explanation -

The program asks user to enter any number n. It passes the number to calculate the nth number of the sequence. The method calculates the next number recursively and returns the result back. The numbers are added into an array to display the sequence.

Code can be found on the Github.

No comments: