Java Fibonacci Sum Calculation

One way to calculate the sum of the first n terms of the Fibonacci sequence is by iterating through each term and adding them together. Below is an example code:

public class Main {
    public static void main(String[] args) {
        int n = 10; // 要求前n项和
        int sum = 0;
        int prev = 0;
        int current = 1;
        
        for (int i = 1; i <= n; i++) {
            sum += current;
            int next = prev + current;
            prev = current;
            current = next;
        }
        
        System.out.println("Fibonacci数列的前" + n + "项和为: " + sum);
    }
}

In the sample code above, we start by defining the desired number of terms ‘n’, then iterate through a loop to calculate each term of the Fibonacci sequence and add them to the ‘sum’ variable. Finally, the output is the sum of the first ‘n’ terms of the Fibonacci sequence.

bannerAds