Fibonacci Series Program in Java

«
»
This is a Java Program to Generate Fibonacci Numbers. The number is said to be in a Fibonacci series if each subsequent number is the sum of the previous two numbers.

Enter the number of terms you want as an input. Now we use for loop to generate the desired series.

Here is the source code of the Java Program to Generate Fibonacci Numbers. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. import java.util.Scanner;
  2. public class Fibonacci 
  3. {
  4.     public static void main(String[] args) 
  5.     {
  6.         int n, a = 0, b = 0, c = 1;
  7.         Scanner s = new Scanner(System.in);
  8.         System.out.print("Enter value of n:");
  9.         n = s.nextInt();
  10.         System.out.print("Fibonacci Series:");
  11.         for(int i = 1; i <= n; i++)
  12.         {
  13.             a = b;
  14.             b = c;
  15.             c = a + b;
  16.             System.out.print(a+" ");
  17.         }
  18.     }
  19. }

Output:

$ javac Fibonacci.java
$ java Fibonacci
 
Enter value of n:5
Fibonacci Series:0 1 1 2 3

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.