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.

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

Java program to print Fibonacci series 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:

fibonacci series program in java using iterative method

Leave a Comment