Task 1: The fibonacci sequence is a famous bit of mathematics, and it happens to
ID: 3572487 • Letter: T
Question
Task 1:
The fibonacci sequence is a famous bit of mathematics, and it happens to have a recursive definition. The first two values in the sequence are 0 and 1 (essentially 2 base cases). Each subsequent value is the sum of the previous two values, so the whole sequence is: 0, 1, 1, 2, 3, 5, 8, 13, 21 and so on. Define a recursive fibonacci(n) method that returns the nth fibonacci number, with n=0 representing the start of the sequence.
Allow the user to input n.
ex. n = 8
0, 1, 1, 2, 3, 5, 8, 13
ex. n = 9
0, 1, 1, 2, 3, 5, 8, 13, 21
Use return method
Need “programmer created class structure”
Use main to control the program
LOOKING FOR THE SUM NOT THE SEQUENCE
Attach Snipping photos of source code and output.
Explanation / Answer
/* This code has been written in java,as there is no any specific demand of language in the question */
import java.util.Scanner;
public class HelloWorld{
/* recursive function to calculate sum of fibonacci sequence */
public static int fibonacci(int n){
/* base cases*/
if(n==1)
return 0;
else if(n==2)
return 1;
/* calling function recursively */
else
return (fibonacci(n-2)+fibonacci(n-1)+1);
}
public static void main(String []args){
/* variable to store user entered number */
int n;
Scanner input=new Scanner(System.in);
/* prompting user to enter number */
System.out.println("Enter number n: ");
n=input.nextInt();
/* calling fibonacci sequence and storing the returned value in sum variable */
int sum=fibonacci(n);
/* printing sum */
System.out.println("sum of fibonacci sequence : "+sum);
}
}
/*****OUTPUT*********
nter number n:
8
sum of fibonacci sequence : 33
Enter number n:
9
sum of fibonacci sequence : 54
******OUTPUT***********/
/* NOTE:Please ask in case of any doubt,would glad to help ,Thanks !! */
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.