Fibonacci Series Using For Loop in Java


Q. Write a Java program to generate Fibonacci Series using for loop

 import java.util.Scanner;

public class FibonacciSeries {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Ask the user how many terms to display
        System.out.print("Enter the number of terms for Fibonacci Series: ");
        int n = scanner.nextInt();

        int first = 0, second = 1;

        System.out.println("Fibonacci Series up to " + n + " terms:");

        for (int i = 1; i <= n; i++) {
            System.out.print(first + " ");
            int next = first + second;
            first = second;
            second = next;
        }

        scanner.close();
    }
}

Q. Write an algorithm to generate Fibonacci Series using for loop

1. Start
2. Read an integer n (number of terms)
3. Initialize first = 0, second = 1
4. Repeat from i = 1 to n:
    a. Print first
    b. Compute next = first + second
    c. Set first = second
    d. Set second = next
5. End
 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.