Print Fibonacci Series in Java

Programming is always a fun and creative task. The more creative you can think the better programmer you will become. However, programming isn’t always about solving problems sometimes there’s also a fun aspect to it which makes it way more satisfying. If you are a programmer then you might have already played with patterns, strings, etc multiple times. Well, it’s also like that you are already familiar with number patterns, but what about printing a Fibonacci Series. In today’s article, we will print Fibonacci Series in Java. With the help of this program, you will be able to print amazing patterns of numbers based on addition. Practising these types of questions also helps to get an upper edge in Competitive Programming.

 

So open up your IDE and let’s get started real quick. Once you understand the logic practice this program on your own to make your brain work in a problem-solving way. This is a simple question, but you might get asked in an interview so make sure to practice it on your own after reading this article.

 

Also Read: Print Mirror Lower Star Triangle in Java

 

What’s The Approach?

 

The most basic and simple approach we’re going to use will need to have your knowledge of using while loop & swapping numbers. As we know the Fibonacci Series starts with 0 1 and the next numbers in this series are the addition of the last two numbers in this series.

 

We will store the first two digits of this series in variables num1 = 0 & num2 = 1 

 

After that we will iterate a while loop,  storing the next element of the series in a variable and printing it out at the same time.

 

Formula  : num3 = num2 + num1

 

Java Program To Print Fibonacci Series

 

Input:

N = 10

 

// Java program for the above approach

class TechDecodeTutorials {

    // Function to print N Fibonacci Number
    static void Fibonacci(int N)
    {
        int num1 = 0, num2 = 1;

        int counter = 0;

        // Iterate till counter is N
        while (counter < N) {

            // Print the number
            System.out.print(num1 + " ");

            // Swap
            int num3 = num2 + num1;
            num1 = num2;
            num2 = num3;
            counter = counter + 1;
        }
    }

    // Driver Code
    public static void main(String args[])
    {
        // Given Number N
        int N = 10;

        // Function Call
        Fibonacci(N);
    }
}

 

Output:

0 1 1 2 3 5 8 13 21 34

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *