Referring back to the assignment from Module 3 on the Fibonacci Numbers, where e
ID: 3925134 • Letter: R
Question
Referring back to the assignment from Module 3 on the Fibonacci Numbers, where each number is the sum of the previous two numbers. Starting from 0 and 1, how do you find the Fibonacci numbers for a given number(index)? It'd be easy to find fib(2) because you know fib(0) and fib(1). Hence, if you know fib(index - 2) and fib(index - 1) you'll be able to find your fib(index).
That way you're applying recursion where for any index number you're entering it would recursively calculate all the way back to 0 and 1. Create a Java program that let's the user enter an index and computes the Fibonacci numbers for that index."
Explanation / Answer
FibonacciNos.java
import java.util.Scanner;
public class FibonacciNos {
public static void main(String[] args) {
//Scanner class object is used to read the inputs entered by the user
Scanner s = new Scanner(System.in);
//getting the index value entered by the user
System.out.print("Enter the value of Index : ");
int n = s.nextInt();
//Displaying the fibonacci Series for the number
System.out.print("The Fibonocci Numbers for the index "+n+" are :");
//This loop will continuously call the fibonacci() method and display the resultant value
for (int i = 0; i <= n; i++) {
//calling the method fibonacci()
System.out.print(fibonacci(i) + " ");
}
}
/*This fibonacci() method will calculate the fibonocci
* numbers recursively and return to the caller
* Params: number of type integer
* Return : fibonocci number of type integer
*/
public static int fibonacci(int index) {
if (index == 0) {
return 0;
} else if (index == 1) {
return 1;
} else {
return fibonacci(index - 1) + fibonacci(index - 2);
}
}
}
_____________________________
Output1:
Enter the value of Index : 8
The Fibonocci Numbers for the index 8 are :0 1 1 2 3 5 8 13 21
______________________________
Output2:
Enter the value of Index : 15
The Fibonocci Numbers for the index 15 are :0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
_____________________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.