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

Top comments (0)