diff --git a/README_fibonacci_recurive.md b/README_fibonacci_recurive.md new file mode 100644 index 0000000000..9f69023845 --- /dev/null +++ b/README_fibonacci_recurive.md @@ -0,0 +1,9 @@ +#Recursive Fibonacci + +In mathematics, the Fibonacci sequence is a sequence in which each number is the sum of the two numbers that precede it. This algorithm prompts the user for how many terms of the sequence they would like to see, then recursively finds and then prints each term of the sequence + +Step 1: Create a for loop from 0 to n, printing out the result from the Fibonacci function each iteration + +Step 2: If you reach the base case n <= 1, return n + +Step 3: If you are not at the base case, recursively call the fibonacci function for n - 1, and n - 2, added together diff --git a/fibonacci_recursive.java b/fibonacci_recursive.java new file mode 100644 index 0000000000..65a3d26dfc --- /dev/null +++ b/fibonacci_recursive.java @@ -0,0 +1,26 @@ +//Recursive Fibonacci Algorithm +import java.util.Scanner; + +public class fibonacci_recursive { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.println("How Fibonacci terms would you like to know? "); + int n = scanner.nextInt(); // Number of Fibonacci terms to generate + System.out.println("The first " + n + " terms in the Fibonacci sequence are: "); + for (int i = 0; i < n; i++) { + System.out.print(fibonacci(i) + " "); + } + System.out.println(); + } + + // Recursive method to calculate the nth Fibonacci number + public static int fibonacci(int n) { + if (n <= 1) { + //Base Case + return n; + } + //Recursive Call + return fibonacci(n - 1) + fibonacci(n - 2); + } + +} \ No newline at end of file