Fibonacci series program in java

ghz 10months ago ⋅ 130 views

Sure, here are Java programs to generate the Fibonacci series using both iteration and recursion:

Using Iteration:

public class FibonacciIteration {

    public static void main(String[] args) {
        int n = 10; // Number of Fibonacci numbers to generate
        generateFibonacci(n);
    }

    public static void generateFibonacci(int n) {
        int a = 0, b = 1;
        System.out.println("Fibonacci Series:");
        for (int i = 0; i < n; i++) {
            System.out.print(a + " ");
            int temp = a + b;
            a = b;
            b = temp;
        }
    }
}

Using Recursion:

public class FibonacciRecursion {

    public static void main(String[] args) {
        int n = 10; // Number of Fibonacci numbers to generate
        System.out.println("Fibonacci Series:");
        for (int i = 0; i < n; i++) {
            System.out.print(fibonacci(i) + " ");
        }
    }

    public static int fibonacci(int n) {
        if (n <= 1) {
            return n;
        } else {
            return fibonacci(n - 1) + fibonacci(n - 2);
        }
    }
}

These programs will generate the first n Fibonacci numbers and print them to the console. Adjust the value of n as needed to generate a different number of Fibonacci numbers.