Fibonacci Series
Print Fibonacci series up to N terms using a loop.
BeginnerTopic: Module 3: Loop Programs
Java Fibonacci Series Program
This program helps you to learn the fundamental structure and syntax of Java programming.
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
Understanding Fibonacci Series
We iteratively update the two previous Fibonacci numbers to generate the next term.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.