CodeHub Menu
Home Age Calculator Exercise Practice About Download Portfolio Play Games NEW Privacy Policy Terms Contact
Login / Register

Fibonacci series

JAVA January 2, 2026 23 views 0 likes
Fibonacci Series in Java

Fibonacci Series in Java

The Fibonacci series is a sequence of numbers in which each number is the sum of the previous two numbers. It is a very common and important topic in computer science and programming.

What Is the Fibonacci Series?

In the Fibonacci series, the first two numbers are usually 0 and 1. Every next number is obtained by adding the previous two numbers.

Example:

0, 1, 1, 2, 3, 5, 8, 13, 21, ...

Objective of the Program

  • Accept the number of terms from the user
  • Generate the Fibonacci series
  • Display the series using a loop

Java Program Code

import java.util.*;

public class FibonacciSeries
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);

        int n, a = 0, b = 1, c;

        System.out.print("Enter number of terms: ");
        n = sc.nextInt();

        System.out.println("Fibonacci Series:");

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

        sc.close();
    }
}
    

Line-by-Line Explanation of the Java Code

1. import java.util.*;

Imports the Scanner class to take input from the user.

2. public class FibonacciSeries

Declares a class named FibonacciSeries. All Java programs must be written inside a class.

3. public static void main(String[] args)

This is the main method where program execution starts.

4. Scanner sc = new Scanner(System.in);

Creates a Scanner object to read input from the keyboard.

5. int n, a = 0, b = 1, c;

Declares variables:

  • n – number of terms
  • a – first Fibonacci number (0)
  • b – second Fibonacci number (1)
  • c – stores the sum of previous two numbers

6. n = sc.nextInt();

Reads the number of terms entered by the user.

7. for (int i = 1; i <= n; i++)

Loop runs n times to generate the Fibonacci series.

8. System.out.print(a + " ");

Prints the current Fibonacci number.

9. c = a + b;

Adds the previous two numbers to generate the next term.

10. a = b; b = c;

Updates values so that the next Fibonacci number can be calculated.

11. sc.close();

Closes the Scanner object. This is good programming practice.

Conclusion

The Fibonacci series program is an excellent example for learning loops, variables, and number logic in Java. It is frequently asked in exams, practicals, and interviews.

Generate Fibonacci Series

© Java Programming Tutorial | Fibonacci Series Example
23 views 0 likes
Total visits: 8,531 • Unique visitors: 3,438