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

https://s3.amazonaws.com/thinkific/file_uploads/288722/images/6b9/ada/897/1600186792956.jpg

So essentially we have 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 8

💻 Fibonacci.java

Previous Section

13.1 Recursion conceptually

Next Section

13.3 Binary Search

<aside> ⚖️ 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 [email protected] for inquiries.

</aside>