Fibonacci series program in Java using iteration

In this tutorial we are going to learn how to print Fibonacci series in Java program using iterative method.

In this series number of elements of the series is depends upon the input of users. Program will print n number of elements in a series which is given by the user as a input.

Read this: What is Fibonacci series? Fibonacci series program using iteration in c.

How this java program will work?

This Java program will take a integer as an input. This input is a number upto which series will print.

Suppose if someone is given input as 5 then output will be

0, 1, 1, 2, 3

Program 1: Fibonacci Series Program in Java using Iterative methods

import java.util.*;  
class Main{
    public static void main(String ...a){
    int first = 0, second = 1, result, i;
    Scanner sc= new Scanner(System.in);
    System.out.print("Enter number- ");  
    int n= sc.nextInt();  
    System.out.println("fibonacci series is: ");
    for (i = 0; i < n; i++)
    {
        if (i <= 1)
            result = i;
        else
        {
            result = first + second;
            first = second;
            second = result;
        }
    System.out.println(result);
    } 
  }
} 

Output:

Enter number- 5
fibonacci series is: 
0
1
1
2
3

Conclusion:

In this tutorial, we have explored writing Fibonacci series program using iterative method in Java. This will generate and print the Fibonacci series. The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1.

Key Points:

  1. User Input:
    • Our above program allows users to input an integer n to determine the number of elements they want in the Fibonacci series.
  2. Iterative Method:
    • Above Java program uses an iterative approach to generate the Fibonacci series.
    • It initializes the first two elements (first and second) to 0 and 1, respectively.
    • The program then uses a for loop to calculate and print each subsequent element in the series.
  3. Logic in Loop:
    • Within the loop, the logic distinguishes between the first two elements and calculates subsequent elements based on the sum of the previous two.
    • The loop continues for n iterations, printing each element of the Fibonacci series.
  4. Output Illustration:
    • The output, illustrated with an example where n is set to 5, demonstrates the generation of the Fibonacci series: 0, 1, 1, 2, 3.

Happy coding! 🚀

Leave a Comment