The Fibonacci sequence is a well-known mathematical sequence in which each term
ID: 3734816 • Letter: T
Question
The Fibonacci sequence is a well-known mathematical sequence in which each term is the sum of the two previous terms. The sequence can be defined as follows:
fib(0) = 0
fib(1) = 1
fib(n) = fib(n-1) + fib(n-2) n>1
Write a recursive method to determine the nth number in the sequence. Put the method in a class called Fib. Note the method should be static. Think why.
File TestFib.java contains the tester. Save this file to your directory. Use it to test your recursive method.
To trace the recursive calling path, add a print statement at the beginning of your fib method that indicates the current parameter, e.g., “Now control is in fib (3)” if the parameter is 3.
// *******************************************************************
// TestFib.java
//
// A simple driver that uses the Fib class to compute the
// nth element of the Fibonacci sequence.
// *******************************************************************
import java.util.Scanner;
public class TestFib
{
public static void main(String[] args)
{
int n, fib;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: ");
n = scan.nextInt();
fib = Fib.Fib(n);
System.out.println("Fib(" + n + ") is " + fib);
}
}
Explanation / Answer
Answer: You need run your TestFib.java class to produce the output.
Fib.java
public class Fib {
public static int Fib(int number){
System.out.println("Now the control is in Fib{"+number+")");
//If number is less than 2
if ((number == 0) || (number == 1)) {
return number;
}else if(number == 2){
return 1;
}else{
//Using recursion
return Fib(number - 1) + Fib(number - 2);
}
}
}
Output:
Enter an integer: 3
Now the control is in Fib{3)
Now the control is in Fib{2)
Now the control is in Fib{1)
Fib(3) is 2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.