The Fibonacci sequence is defines as follows f0 0 f1 1 and

The Fibonacci sequence is defines as follows.

f(0) = 0, f(1) = 1, and f(n) = f(n – 1) + f(n-2) if n > 1.

Write a recursive method and an iterative method to computer any term

in the Fibonacci sequence. Here are the signatures of the two methods.

public static int FibR( int n).

public static int FibI( int n).

A sample run of your program is as follows.

Input an integer for the index of a term in the Fibonacci sequence.

10

the 11-th term \"55\" in the Fibonacci sequence can be computed recursively.

the 11-th term \"55\" in the Fibonacci sequence can be computed iteratively.

Solution

Hi, Please find my implementation.

Please let me know in case of any issue.

public class Fibonacci {

  

   public static int FibR( int n){

      

       if (n == 1)

          return 0;

       if(n == 2)

           return 1;

       return FibR(n-1) + FibR(n-2);

   }

   public static int FibI( int n){

      

       if (n == 1)

          return 0;

       if(n == 2)

           return 1;

      

       int f1 = 0;

       int f2 = 1;

       int fib = 0;

       for(int i=3; i<=n; i++){

           fib = f1 + f2;

           f1 = f2;

           f2 = fib;

       }

      

       return fib;

   }

  

   public static void main(String[] args) {

      

       for(int i=1; i<=11; i++){

           System.out.println(\"FibI(\"+i+\"): \"+FibI(i));

           System.out.println(\"FibR(\"+i+\"): \"+FibR(i));

       }

   }

}

/*

Sample run:

FibI(1): 0

FibR(1): 0

FibI(2): 1

FibR(2): 1

FibI(3): 1

FibR(3): 1

FibI(4): 2

FibR(4): 2

FibI(5): 3

FibR(5): 3

FibI(6): 5

FibR(6): 5

FibI(7): 8

FibR(7): 8

FibI(8): 13

FibR(8): 13

FibI(9): 21

FibR(9): 21

FibI(10): 34

FibR(10): 34

FibI(11): 55

FibR(11): 55

*/

The Fibonacci sequence is defines as follows. f(0) = 0, f(1) = 1, and f(n) = f(n – 1) + f(n-2) if n > 1. Write a recursive method and an iterative method to
The Fibonacci sequence is defines as follows. f(0) = 0, f(1) = 1, and f(n) = f(n – 1) + f(n-2) if n > 1. Write a recursive method and an iterative method to
The Fibonacci sequence is defines as follows. f(0) = 0, f(1) = 1, and f(n) = f(n – 1) + f(n-2) if n > 1. Write a recursive method and an iterative method to

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site