Respuesta :
Answer:
//import Scanner class
import java.util.Scanner;
//Class header definition
public class Fibonacci_Series {
//main method
public static void main(String[] args) {
//create an object of the Scanner class to allow for user's input
Scanner input = new Scanner(System.in);
//Ask the user to enter the number of terms
System.out.println("Enter the number of terms");
//Assign user input to a variable
int nTerms = input.nextInt();
//Declare and initialize to zero a variable sum to hold the sum of the series.
int sum = 0;
//Show message
System.out.println("First " + nTerms + " terms of Fibonacci numbers are");
//Create a for loop that cycles as many times as the number of terms entered by user
//At every term (cycle), call the fibonacci method on the term.
//And add the number to the sum variable
for (int i = 1; i <= nTerms; i++){
System.out.println(fibo(i));
sum = sum + fibo(i);
} //End of for loop
//show message
System.out.println("The sum of the above sequence is ");
//Display the sum of the fibonacci series
System.out.println(sum);
} //End of main method
//Method fibo to return the nth term of the fibonacci series
public static int fibo(int n){
//if n = 1,
// the fibonacci number is 0
if (n <= 1){
return 0;
}
//if n = 2,
// the fibonacci number is 1
else if(n == 2){
return 1;
}
//if n > 2, fibonacci number is the sum of the previous two numbers
else {
return fibo(n-1) + fibo(n-2);
}
} // End of method fibo
} // End of class declaration
Sample Output:
Enter the number of terms
>> 6
First 6 terms of Fibonacci numbers are
0
1
1
2
3
5
The sum of the above sequence is
12
Explanation:
The above code has been written in Java.
The code contains comments explaining important parts of the code. Kindly go through the comments for better readability and understanding.
The source code file of this question has been attached to this response. Please download it and go through it for better formatting.