Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a methodcalled fibonacci which takes an integer as an argument representin

ID: 3611323 • Letter: W

Question

Write a methodcalled fibonacci which takes an integer as an argument representingthe nth Fibonacci number to be calculated and returns an integerrepresenting the Fibonacci number in that position of thesequence.

System.out.print(f[0] +" " + f[1] + " "); //outputs the first 2 elements in arrayf


for(x=2; x<=45; x++) //notice 'x<=45' not 46 has to be 45 ifany higher cannot handle array
{
f[x] = f[x-1] + f[x-2];//calculates next element inarray

System.out.println(f[x]);//output next elements in array 2-45

}
}
}

Explanation / Answer


import javax.swing.JOptionPane;

/*
    This program computes Fibonacci numbers using arecursive
    method.
*/
public class Fibonacci
{
    public static void main(String[] args)
    {
       String input =JOptionPane.showInputDialog("Enter n: ");
       int n =Integer.parseInt(input);

       for (int i = 1; i <= n;i++)
       {
          int f =fib(i);
         System.out.println("fib(" + i + ") = " + f);
       }
       System.exit(0);
      
    }

    /**
       Computes a Fibonaccinumber.
       @param n an integer
       @return the nth Fibonaccinumber
    */
    public static int fib(int n)
    {
       if (n <= 2)
           return 1;
       else
           return fib(n - 1) + fib(n - 2);
    }
}
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote