Java Online Compiler
Example: Fibonacci Series using for loop in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Fibonacci Series using for loop import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Initialize Scanner for user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt user for the number of terms System.out.print("Enter the number of terms (n): "); int n = scanner.nextInt(); // Step 3: Initialize the first two Fibonacci numbers int a = 0; int b = 1; // Step 4: Handle edge cases for n = 0, 1, 2 if (n <= 0) { System.out.println("Please enter a positive integer."); } else if (n == 1) { System.out.println("Fibonacci Series up to 1 term: " + a); } else { // Step 5: Print the first two terms System.out.print("Fibonacci Series up to " + n + " terms: " + a + ", " + b); // Step 6: Generate subsequent terms using a for loop for (int i = 2; i < n; i++) { int nextTerm = a + b; System.out.print(", " + nextTerm); a = b; b = nextTerm; } System.out.println(); // New line for better formatting } // Step 7: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS