Task: Write a Fibonacci Program in Java to print n terms of Fibonacci series. The user will input the number of Fibonacci terms to print, at run time. Use Scanner class of java.util to get input from user through key board.
The Source code of Fibonacci Program in Java to print n terms
/* * Write a Java Program to print Fibonacci series upto n terms. The user will enter the number of terms required at run time. */ package fibonacciseries; import java.util.Scanner; /** * @author www.EasyCodeBook.com */ public class FibonacciSeries { public static void main(String[] args) { int term1=0, term2=1, term3, n, i; Scanner input = new Scanner(System.in); System.out.print("Enter Number of Fibonacci Terms to print:"); n = input.nextInt(); for(i=1;i<=n;i++) { System.out.print(term1+", "); term3 = term1 + term2; term1 = term2; term2 = term3; } } }
The sample run and output:
Enter Number of Fibonacci Terms to print:9
0, 1, 1, 2, 3, 5, 8, 13, 21,