Answer:
//import the Scanner class
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
//create an object of the Scanner class
Scanner input = new Scanner(System.in);
//Prompt the user to enter the number of terms
System.out.println("Enter the number of terms");
//Store the user input in a variable
int noOfTerms = input.nextInt();
//Create a variable sum to hold the sum of the series.
int sum = 0;
//Display message
System.out.println("First " + noOfTerms + " terms of Fibonacci numbers are");
//Create a loop that goes as many times as the number of terms
//At every term (cycle), call the fibonacci method on the term.
//And add the number to the sum variable
for (int i = 1; i<=noOfTerms; i++){
System.out.println(fibonacci(i));
sum += fibonacci(i);
}
//Display a message
System.out.println("The sum of the above sequence is ");
//Display the sum of the fibonacci series
System.out.println(sum);
}
//Create a method fibonacci to return the nth term of the fibonacci series
public static int fibonacci(int n){
//when n = 1, the fibonacci number is 0
if (n <= 1){
return 0;
}
//when n = 2, the fibonacci number is 1
else if(n == 2){
return 1;
}
//at other terms, fibonacci number is the sum of the previous two numbers
else {
return fibonacci(n-1) + fibonacci(n-2);
}
} // End of fibonacci method
} // End of class declaration
Sample Output:
>> Enter the number of terms
7
>> First 7 terms of Fibonacci numbers are
0
1
1
2
3
5
8
>> The sum of the above sequence is
20
Step-by-step explanation:
The above code has been written in Java. It contains comments explaining important parts of the code. Please go through the code through the comments for understandability.