6.32 LAB: Fibonacci sequence (EO) The Fibonacci sequence begins with 0 and then 1 follows. All subsequent values are the sum of the previous two, for example: 0, 1, 1, 2, 3, 5, 8, 13. Complete the fibonacci() method, which has an index, n, as parameter and returns the nth value in the sequence. Any negative index values should return -1. Ex: If the input is: 7 the output is: fibonacci (7) is 13 Note: L Ise a for loon and DO NOT use recursion
My Issue:
I don't get why this is illegal start of type (i<0; i < n; i++) as it's the standard of the for loop. I also don't understand how Public Static fibonnacci (int n) { is illegal as the public static is meant to make it accessible in the main method.
My code:
import java.util.Scanner;
public class FibonacciSequence {
public static fibonnacci(int n) {
/* Type your code here. */ public static fibonnacci (int n) {
int num1=0; // My logic of the fibonnacci: 0 1 1 2 3 5 ,so 0(num1)+1(num2)=1(num3), 1(num1)+1(num2)=2(num3)
int num2=1;
int num3;
int sum=0;
if (n < 0) {
return -1;
}
for (i < 0; i < n; i++) {
sum = num1 + num2;
num2=num3;
num3=sum;
}
return sum;
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
FibonacciSequence
int startNum;
startNum = scnr.nextInt();
System.out.println("fibonnacci(" + startNum + ") is " + program.fibonacci(startNum));
}
}
Trending now
This is a popular solution!
Step by step
Solved in 2 steps with 1 images