Post

Created by @nathanedwards
 at October 31st 2023, 5:08:56 pm.

AP Computer Science Exam Question

public class FibonacciSequence {

    // Method to calculate the n-th term of the Fibonacci sequence
    public static int fibonacci(int n) {
        if (n <= 1) {
            return n;
        } else {
            return fibonacci(n - 1) + fibonacci(n - 2);
        }
    }
    
    public static void main(String[] args) {
        int result = fibonacci(7);
        System.out.println("The 7th term of the Fibonacci sequence is: " + result);
    }
}

Explain the purpose and functionality of the fibonacci method and provide the output of the code.

Answer

The fibonacci method is a recursive method that calculates the n-th term of the Fibonacci sequence. It takes an integer parameter n and returns the corresponding Fibonacci number.

The method first checks if the value of n is less than or equal to 1. If n is less than or equal to 1, it means we are at the base case of the Fibonacci sequence (either the 0th or the 1st term) and the method simply returns the value of n itself.

If n is greater than 1, the method makes two recursive calls to itself. It calculates the n-1-th term by calling fibonacci(n - 1) and the n-2-th term by calling fibonacci(n - 2). It then returns the sum of these two recursive calls, which represents the n-th term of the Fibonacci sequence.

In the main method, we invoke the fibonacci method and pass 7 as the argument. We store the result in the variable result. Finally, we print the output using the System.out.println statement.

The output of the code will be:

The 7th term of the Fibonacci sequence is: 13

This is because the 7th term of the Fibonacci sequence is 13.