Fibonacci sequence.java Write a program that computes the Fibonacci number for s
ID: 3759888 • Letter: F
Question
Fibonacci sequence.java
Write a program that computes the Fibonacci number for some input integer. 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 theindex 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
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Fibonacci
{
public static int fibonacciRec(int n) {
int z = 0;
if(n<0)
return -1;
else if (n==0)
return 0;
else if (n==1)
return 1;
else if (n>1)
{
z = fibonacciRec(n-1) + fibonacciRec(n-2);
}
return z;
}
public static int fibonacciIte(int n) {
if(n<0)
return -1;
else if (n==0)
return 0;
else if (n==1)
return 1;
else if (n>1)
{
int x = 0,y = 1,temp,z = 0;
int i = 1;
while(i!=n)
{
z = x+y;
i++;
x = y;
y = z;
}
return z;
}
return 0;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int number;
Scanner input = new Scanner(System.in);
System.out.println("Please input a positive integer.");
String line;
while(true)
{
line = input.nextLine();
try
{
number = Integer.parseInt(line);
if(number>0)
break;
else
System.out.println("Please input a positive integer.");
}
catch(NumberFormatException e)
{
System.out.println("Cannot parse the input as an integer.Please Input Again");
}
}
System.out.println("Fibonacci number at index " + number + " using recursion is : " + fibonacciRec(number));
System.out.println("Fibonacci number at index " + number + " using iteration is : " + fibonacciIte(number));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.