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
nfrom the user. - Initialize two variables to store the current and previous values of the Fibonacci series. Assign the current value as
1and the previous value as0. - If the value of
nis0, return0. If it is1, return1. If it is greater than1, use one loop to find the sum. - Create one
sumvariable and initialize it as0. By using a loop, find the sum of all values up to thenth member of the series and assign that value to thesumvariable. - Print the
sumvariable 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:
- Initialize a variable
nto store the value of n. It also created anotherScannervariable to read the user input. The user-entered value is assigned to the variablen. - It calls the
findSummethod to calculate the sum. ThefindSummethod takes the value ofnas a parameter and returns the sum. - The
findSummethod initializes four integer variables,currentValueto assign the current value of the series,prevValueto assign the previous value of the series,sumto assign the sum, andtempto use as a temporary storage variable. - If the value of
nis less than or equal to0, it returns 0. If the value ofnis equal to 1, it returns 1. - It initializes the value of the
sumvariable as 1. It runs one loop fromi = 2toi = 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 = 1Method 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
findSumfunction is a recursive function. It calculates the sum of the firstnnumbers of the Fibonacci series. - The
findSumfunction takes the current value, previous value,ii.e. the current index andnas its parameters. - It returns 0 if the value of
nis 0, 1 if the value ofnis 1, and 0 if the value ofiis equal ton. Else, it adds thecurrentValuewith the result offindSum, i.e. it calls itself recursively. - On the next call, it updates the current value as the sum of current and previous values, and
currentValueas theprevValue.
If you run this program, it will give a similar result as the above examples.
You might also like:
- Java HashMap.merge() method explanation with examples
- Java program to convert a boolean array to string array
- 5 Different ways to append text to a file in Java
- Can Enum implements interfaces in Java
- Java program to find special numbers in a range
- Create a Rectangle class in Java and calculate area, perimeter
- Java program to check if a number is special or not

