Fibonacci Series

Print Fibonacci series up to N terms using a loop.

JavaBeginner
Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number of terms: ");
        int n = sc.nextInt();

        int a = 0, b = 1;
        for (int i = 1; i <= n; i++) {
            System.out.print(a + " ");
            int c = a + b;
            a = b;
            b = c;
        }
        sc.close();
    }
}

Output

Enter number of terms: 7
0 1 1 2 3 5 8

We iteratively update the two previous Fibonacci numbers to generate the next term.