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

I need java not C++: Write a program that computes the Fibonacci number for some

ID: 3759242 • Letter: I

Question

I need java not C++: Write a program that computes the Fibonacci number for some input integer. (See segments 7.37 – 7.41 in your book for some info on the Fibonacci sequence or you can look it up on the Internet). The sequence is defined as the first two elements are each 1, after that each element in the sequence is the sum of the previous two elements. The first few numbers of the sequence are 1,1,2,3,5,8,13,21,34,55,… Your assignment is to write a program with a main method and two additional methods. The main method will request the index into the Fibonacci sequence that is desired and verify that it is a positive integer. If it is not a positive integer, it will request that the use input a number again. Note that I will test this using letters, decimal numbers, negative integers, etc. and it must handle these problems without erroring off. It will do so until the use inputs a positive integer. It will then invoke the two methods each of which will compute the required Fibonacci number. One method will use recursion to do so and another will use iteration. Your main method will output the determined Fibonacci number from each of the methods (they had better be the same).

Explanation / Answer

import java.util.Scanner;

public class Fib{
   public static void main(String[] args)
   {
       Scanner s = new Scanner(System.in);
       System.out.println("Enter the value of n: ");
       int n = s.nextInt();
       while(n<=0)

       {
           System.out.println("Please input correct integer which should be grater than 0");
          n = s.nextInt();
       
       }
       System.out.println("Using Iteration "+fibonacci_Itr(n));
       System.out.println("Using Iteration "+fibonacci_rec(n));

   }


   public static int fibonacci_Itr(int n) {
       if (n == 0) {
           return 0;
       } else if (n == 1) {
           return 1;
       } else {
           int a = 0;
           int b = 1;
           for (int i = 1; i < n; i++) {
               int nextNumber = a + b;
               a = b;
               b = nextNumber;
           }
           return b;
       }
   }

   public static int fibonacci_rec(int n) {
       if (n == 0) {
           return 0;
       } else if (n == 1) {
           return 1;
       } else {
           return fibonacci_rec(n - 1) + fibonacci_rec(n - 2);
       }
   }





}