Core Java Concepts and Syntax

Print Fibonacci Series in JAVA

Print Fibonacci Series in JAVA

Introduction

In Java, the Fibonacci series is a program that returns a Fibonacci series of N numbers when given an integer input N. To solve a Fibonacci Series problem, it is essential to understand what a Fibonacci Series is.

What is a Fibonacci series in Java?

The Fibonacci series in Java consists of numbers, with every third number being the sum of the two previous numbers. Here is an example of the Fibonacci series

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... n

Here, adding the two last numbers leads to the following number. i.e., adding the two numbers before 13 results in 13, hence (5+8). In the same way, 21 can be obtained by adding two numbers before it (8+13), Furthermore, 34 is (13+21).

Ways to Display Fibonacci Series in Java

Fibonacci series programs can be written in Java in two ways:

Finding Fibonacci series in Java: Without Recursion

public class FibonacciwithoutRecursion {
    public static void main(String args[]) {
        int x1=0,x2=1,x3,j,count=10;
        System.out.print(x1+" "+x2);

        for(j=2; j<count; ++j) {
            x3=x1+x2;
            System.out.print(" "+x3);
            x1=x2;
            x2=x3;
        }

    }
}
Output
0 1 1 23 5 8 13 21 34

write your code here: Coding Playground

Finding Fibonacci series in Java: With Recursion

public class FibonacciWithRecursion {
    static int x1=0,x2=1,x3=0;
    static void displayFibonacci(int count) {
        if(count>0) {
            x3 = x1 + x2;
            x1 = x2;
            x2 = x3;
            System.out.print(" "+x3);
            displayFibonacci(count-1);
        }
    }
    public static void main(String args[]) {
        int count=10;
        System.out.print(x1+" "+x2);
        displayFibonacci(count-2);
    }
}
Output
0 1 1 23 5 8 13 21 34

write your code here: Coding Playground

Code Sample

Here is the code that can display the Fibonacci series until a specific value is reached

import java.util.Scanner;
public class Fibonacci {
    public static void main(String[] args) {
        int n, x = 0, y = 0, z = 1;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter the value of n:");
        n = s.nextInt();
        System.out.print("Fibonacci Series:");
        for(int k = 1; k <= n; k++) {
            x = y;
            y = z;
            z = x + y;
            System.out.print(x+" ");
        }
    }
}
Output
Enter the value of n:15
Fibonacci Series:0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 

write your code here: Coding Playground