Find the sum of the N Fibonacci Numbers
Write a Java program to find the sum of the first N numbers in the Fibonacci series.
package Fibonacciseries;
import java.util.Scanner;
public class FibonacciSum
{ public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the
value of N: ");
int N = scanner.nextInt();
// Call the method to calculate
the sum of the first N Fibonacci numbers
int sum = calculateFibonacciSum(N);
System.out.println("The sum
of the first " + N + " Fibonacci numbers is: " + sum);
}
public static int calculateFibonacciSum(int N)
{
if (N <= 0)
{
return 0;
}
int sum = 0;
int prev = 0;
int current = 1;
for (int i = 0; i < N; i++)
{
sum += current; // Add the
current number to the sum
int next = prev + current; // Calculate
the next Fibonacci
number
prev = current; // Update the 'prev'
value for the next iteration
current = next; // Update the
'current' value for the next iteration
}
return sum;
}
}
Output :
Enter the value of
N: 10
The sum of the
first 10 Fibonacci numbers is: 143
Explanation:
1.We first import the java.util.Scanner class to take input from the user.2.We create a class named FibonacciSum that contains the main method.
3.Inside the main method, we prompt the user to enter the value of N, which represents the number of Fibonacci numbers we want to sum.
4.We call the calculateFibonacciSum method and pass the value of N as an argument.
5.The calculateFibonacciSum method takes an integer N as input and returns the sum of the first N Fibonacci numbers.
6.We initialize sum, prev, and current to 0, 0, and 1, respectively.
7.We use a for loop to generate the Fibonacci numbers up to the Nth number.
8.In each iteration, we add the current number to the sum.
9.We then calculate the next Fibonacci number by adding prev and current, and update the values of prev and current for the next iteration.
10.After the loop, we return the sum, which holds the sum of the first N Fibonacci numbers.
11.Finally, we print the result in the main method.
Comments
Post a Comment