Fibonacci
The Fibonacci sequence is where each number is the sum of the two preceding it. We can write this recursively the way we did below. Our base case would be when we get to the n = 1, and our recursive case would be whenever n < 2
// Fibonacci Series using Recursion class fibonacci { public static int fibonacci(int n) { if (n < 2) return; return fibonacci(n-1) + fibonacci(n-2); } public static void main (String args[]) { int n = 6; System.out.println(fibonacci(n)); } }
To understand a recursive problem, we can once again create a flowchart.
So we have n = 6
So essentially we have 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 8
Copyright © 2021 Code 4 Tomorrow. All rights reserved.
The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.