Fibonacci Series in Java
Print Fibonacci series up to N terms using a loop.
BeginnerModule 3: Loop ProgramsExample 10 of 25
fibonacci-series.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Enter number of terms: ");7 int n = sc.nextInt();89 int a = 0, b = 1;10 for (int i = 1; i <= n; i++) {11 System.out.print(a + " ");12 int c = a + b;13 a = b;14 b = c;15 }16 sc.close();17 }18}
Output
Enter number of terms: 7 0 1 1 2 3 5 8
What's going on
We iteratively update the two previous Fibonacci numbers to generate the next term.