3 ways in Java to find the sum of Fibonacci series

How to find the sum of 0, 1, 1, 2, 3, 5, 8.. or Fibonacci series in Java:

In this post, we will learn how to find the sum of the Fibonacci series up to a specific distance. The Fibonacci series or Fibonacci sequence is a series of numbers where each number is equal to the sum of two previous numbers. The first two numbers of the Fibonacci series are 0 and 1.

For example, 0, 1, 1, 2, 3, 5, 8.... is a Fibonacci series.

We will write one Java program that will find the sum of this series up to the nth series item. This program will take the value of n as input from the user and it will print the sum.

For example, if n is 5, then the sum will be 0+1+1+2+3 = 7.

Algorithm to print the sum of the Fibonacci series:

The program will use the following algorithm to find the sum of the first n values of the Fibonacci series:

  • Get the value of n from the user.
  • Initialize two variables to store the current and previous values of the Fibonacci series. Assign the current value as 1 and the previous value as 0.
  • If the value of n is 0, return 0. If it is 1, return 1. If it is greater than 1, use one loop to find the sum.
  • Create one sum variable and initialize it as 0. By using a loop, find the sum of all values up to the nth member of the series and assign that value to the sum variable.
  • Print the sum variable at the end of the program.

Method 1: Java program to get the sum of the first n items of the Fibonacci series with a for loop:

Below is the complete Java program:

import java.util.Scanner;

class Main {

    private static int findSum(int n) {
        // 3
        int currentValue = 1, prevValue = 0, temp;

        // 4
        if (n <= 0)
            return 0;

        if (n == 1)
            return 1;

        // 5
        int sum = 1;
        for (int i = 2; i < n; i++) {
            temp = currentValue;
            currentValue = prevValue + currentValue;
            prevValue = temp;

            sum += currentValue;
        }
        return sum;
    }

    public static void main(String[] args) {
        try (Scanner sc = new Scanner(System.in)) {
            // 1
            int n;
            System.out.println("Enter the value of n: ");
            n = sc.nextInt();

            // 2
            System.out.println("Sum = " + findSum(n));
        }
    }
}

Download it on GitHub

Explanation:

The commented numbers in the above program denote the step numbers below:

  1. Initialize a variable n to store the value of n. It also created another Scanner variable to read the user input. The user-entered value is assigned to the variable n.
  2. It calls the findSum method to calculate the sum. The findSum method takes the value of n as a parameter and returns the sum.
  3. The findSum method initializes four integer variables, currentValue to assign the current value of the series,prevValue to assign the previous value of the series, sum to assign the sum, and temp to use as a temporary storage variable.
  4. If the value of n is less than or equal to 0, it returns 0. If the value of n is equal to 1, it returns 1.
  5. It initializes the value of the sum variable as 1. It runs one loop from i = 2 to i = n - 1. We have already initialized the values of the first and the second variables of the series. So, we are running the loop from the third element.

Inside the loop, it assigns the value of currentValue to temp, updates the value of currentValue as the sum of the previous two values, and assigns the value of temp to prevValue. It adds the value of currentValue to the sum variable. Since the sum variable is initialized as 1, it was assigned the sum of the first two numbers before the loop starts. We are adding the values of the Fibonacci series starting from i = 2 inside the loop. It returns the value of the sum variable once the loop ends.

Sample output:

If you run this program, it will print outputs as below:

Enter the value of n: 
7
Sum = 20

Enter the value of n: 
0
Sum = 0

Enter the value of n: 
1
Sum = 1

Method 2: Java program to get the sum of the first n elements of the Fibonacci series using a while loop:

We can also use any other loop to find the sum of the first n elements of the Fibonacci series. For example, the below program uses a while loop to find the sum.

import java.util.Scanner;

class Example2 {

    private static int findSum(int n) {
        int currentValue = 1, prevValue = 0, sum = 0, temp;

        if (n <= 0)
            return 0;

        if (n == 1)
            return 1;

        sum = 1;
        int i = 2;
        while (i < n) {
            temp = currentValue;
            currentValue = prevValue + currentValue;
            prevValue = temp;

            sum += currentValue;
            i++;
        }
        return sum;
    }

    public static void main(String[] args) {
        try (Scanner sc = new Scanner(System.in)) {
            System.out.println("Enter the value of n: ");
            int n = sc.nextInt();

            System.out.println("Sum = " + findSum(n));
        }
    }
}

Download it on GitHub

This example is similar to the previous program. The only difference is that we are using a while loop instead of a for loop. It initializes the variable i as 2 before the loop starts and works similarly.

If you run this program, it will give similar output.

Method 3: Recursive Java program to find the Fibonacci series sum of first n items:

We can also find this sum recursively. A recursive program calls itself again and again until it finds the result. Let’s take a look at the below program:

import java.util.Scanner;

class Example3 {

    private static int findSum(int currentValue, int prevValue, int i, int n) {
        if (n <= 0)
            return 0;
        if (n == 1)
            return 1;

        if (i == n)
            return 0;

        return currentValue + findSum(currentValue + prevValue, currentValue, i + 1, n);
    }

    public static void main(String[] args) {
        try (Scanner sc = new Scanner(System.in)) {
            System.out.println("Enter the value of n: ");
            int n = sc.nextInt();

            System.out.println("Sum = " + findSum(1, 0, 1, n));
        }

    }
}

Download it on GitHub

  • The findSum function is a recursive function. It calculates the sum of the first n numbers of the Fibonacci series.
  • The findSum function takes the current value, previous value, i i.e. the current index and n as its parameters.
  • It returns 0 if the value of n is 0, 1 if the value of n is 1, and 0 if the value of i is equal to n. Else, it adds the currentValue with the result of findSum, i.e. it calls itself recursively.
  • On the next call, it updates the current value as the sum of current and previous values, and currentValue as the prevValue.

If you run this program, it will give a similar result as the above examples.

Java find the sum of first n items of Fibonacci series recursively

You might also like: