DEV Community

Code Green
Code Green

Posted on

Fibonacci Series - Coding Interview Question | Easy visual explanation

New Coding Video: Fibonacci Series in Java

We just released a new coding tutorial video on our YouTube channel where we walk through how to code the Fibonacci series in Java. The Fibonacci sequence is a classic programming problem that is great for practicing your coding skills.

Image description

Link to youtube video: https://youtu.be/Naike24f-sw

Algorithm for Fibonacci series, print for given n numbers:

  1. Consider n = 9
  2. num1 = 0, num2 = 1; print (num1,num2)
  3. Iterate using for loop till n-2: for i=0 to n-2 (i.e. 7)
  4. Calculate sum = num1 + num2 ; print sum
  5. move num1 to num2, & num2 to sum
  6. num1 = num2, num2 = sum

Code


private static void printFibonacci(int n)
    {

        int num1 = 0;
        int num2 = 1;

        System.out.print(num1+" "+num2+" ");

        for (int i = 0; i < n-2; i++) {

            int sum = num1 + num2;
            System.out.print(sum+" ");

            num1 = num2;
            num2 = sum;

        }



    }

Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay