Rewrite the fib method in Listing 1 using tail recursion.
LISTING 1 ComputeFibonacci.java
1 import java.util.Scanner;
2
3 public class ComputeFibonacci {
4 /** Main method */
5 public static void main(String[] args) {
6 // Create a Scanner
7 Scanner input = new Scanner(System.in);
8 System.out.print("Enter an index for a Fibonacci number: ");
9 int index = input.nextInt();
10
11 // Find and display the Fibonacci number
12 System.out.println("The Fibonacci number at index "
13 + index + " is " + fib(index));
14 }
15
16 /** The method for finding the Fibonacci number */
17 public static long fib(long index) {
18 if (index == 0) // Base case
19 return 0;
20 else if (index == 1) // Base case
21 return 1;
22 else // Reduction and recursive calls
23 return fib(index - 1) + fib(index - 2);
24 }
25 }
![]()
![]()
![]()
We need at least 10 more requests to produce the solution.
0 / 10 have requested this problem solution
The more requests, the faster the answer.