fibonacci series – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Tue, 29 Sep 2020 11:23:47 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg fibonacci series – Programmerbay https://programmerbay.com 32 32 Java program to print Fibonacci series https://programmerbay.com/java-program-to-print-fibonacci-series/ https://programmerbay.com/java-program-to-print-fibonacci-series/#respond Tue, 07 Jul 2020 06:42:38 +0000 https://www.programmerbay.com/?p=4146 The program prints Fibonacci Series as the output . The functionality can be achieved in two ways by simply using a loop or recursion. Lets first get into Loops

  • Fibonacci Series Using For Loop
  • Fibonacci Series Using While Loop

A series is said to be Fibonacci series if each and every number in the given series is figured out by adding two immediate previous numbers. Here’s the sequence,  0, 1, 1, 2, 3, 5, 8, 13, 21 and so on.

Java program to print Fibonacci series using For Loop

Program:

public class FibonacciSeries {
    public static void main(String[] args) {
        int sum, firstNum = 0, secondNum, range = 10;
        System.out.println(" Fibonacci Series : ");
        secondNum = 1;
        for (int i = 1; i <= range; i++) {
            System.out.print(firstNum+" ");
            sum = firstNum + secondNum;
            firstNum = secondNum;
            secondNum = sum;
        }
}
}

Java program to print Fibonacci series using While Loop

program :

public class FibonacciSeries {
    public static void main(String[] args) {
        int sum, firstNum = 0, secondNum, range = 10, i=0;
        System.out.println(" Fibonacci Series : ");
        secondNum = 1;
        while(i <= range) {
            System.out.print(firstNum + " ");
            sum = firstNum + secondNum;
            firstNum = secondNum;
            secondNum = sum;
            i++;
        }
    }
}

Output:

Fibonacci Series : 
0 1 1 2 3 5 8 13 21 34

 

Another approach is to print the Fibonacci series recursively. In this, a method calls itself until a condition turns to false. Here’s is the code that does the same.

Java program to print Fibonacci series using recursion 

program: 

public class FibonacciSeries {
    public static void main(String[] args) {
        int firstNum = 0, secondNum = 1, range = 10;
        System.out.println(" Fibonacci Series : ");
        printFibonacciSeriesRecursively(firstNum, secondNum, range);
    }

    static void printFibonacciSeriesRecursively(int num1, int num2, int range) {
        if (range < 1) {
            return;
        } else {
            System.out.print(num1 + " ");
        }
        printFibonacciSeriesRecursively(num2, (num1 + num2), range - 1);
    }
}

 

Output:

Fibonacci Series : 
0 1 1 2 3 5 8 13 21 34

]]>
https://programmerbay.com/java-program-to-print-fibonacci-series/feed/ 0