Java program to display fibonacci series

www.igift‮di‬ea.com

Here is a Java program to display the Fibonacci series:

import java.util.Scanner;

public class FibonacciSeries {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of terms in the Fibonacci series: ");
        int n = scanner.nextInt();
        scanner.close();

        int firstTerm = 0, secondTerm = 1;
        System.out.print("Fibonacci series up to " + n + " terms: " + firstTerm + " " + secondTerm);

        for (int i = 2; i < n; i++) {
            int nextTerm = firstTerm + secondTerm;
            System.out.print(" " + nextTerm);
            firstTerm = secondTerm;
            secondTerm = nextTerm;
        }
    }
}

In this program, we first prompt the user to enter the number of terms in the Fibonacci series using the Scanner class.

We then initialize two variables firstTerm and secondTerm to 0 and 1 respectively, which are the first two terms of the Fibonacci series. We print these two terms as the starting point of the series.

We then use a for loop to iterate over the remaining terms in the series. For each iteration, we calculate the next term in the series by adding the previous two terms. We then print the next term and update firstTerm and secondTerm to the values of the previous two terms.

The output of this program will be:

Enter the number of terms in the Fibonacci series: 10
Fibonacci series up to 10 terms: 0 1 1 2 3 5 8 13 21 34

You can replace 10 with any other positive integer to display the Fibonacci series up to that number of terms.