Fibonacci Series in Java - The Coding Shala

Home >> Java Programs >> Fibonacci Series

 Hey there, welcome back to another post. In this post, we are going to learn how to display or print the Fibonacci series till nth elements using the Java program.

Fibonacci Series in Java

Write a Java program to print the Fibonacci Series till nth element. Consider first and the second element of the Fibonacci series are 0 and 1.

Example 1: 

Input: 5
Output: [0, 1, 1, 2, 3]

Solution

As we know, in the Fibonacci series the current element is the sum of the previous two elements. We can store all the Fibonacci elements in the array and using for loop we can generate all the series's elements.

fib[i] = fib[i-1] + fib[i-2]

where, fib[0] = 0, and fib[1] = 1

Java Program: 

/**
 * https://www.thecodingshala.com/
 */

import java.util.*;

public class Main {

    public static void printFib(int n) {
        int[] fib = new int[n];
        fib[0] = 0;
        fib[1] = 1;

        for(int i=2; i<n; i++) {
            fib[i] = fib[i-1] + fib[i-2];
        }

        System.out.println("Fibonacci Series is:");
        for (int num : fib) {
            System.out.print(num + " ");
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter n, where n is number of elements in the Fibonacci Series");
        int n = sc.nextInt();
        printFib(n);
    }
}

Output: 

Enter n, where n is number of elements in the Fibonacci Series
10
Fibonacci Series is:
0 1 1 2 3 5 8 13 21 34 

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Single Number 3 LeetCode Solution - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala