Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added algorithm for recursive fibonacci #6829

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README_fibonacci_recurive.md
Original file line number Diff line number Diff line change
@@ -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
26 changes: 26 additions & 0 deletions fibonacci_recursive.java
Original file line number Diff line number Diff line change
@@ -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);
}

}