Java Programs

Fibonacci series program using iteration

In Java, we will learn how to output the Fibonacci series in a Java program using recursion.

Its logic is different from that of the Fibonacci series program in C, which uses iteration.

Here we have a function called fibonacci() that is recursive. Each time it calls itself to calculate the elements of the series.

This fibonacci series program takes an integer as input. And prints the series up to the given input.

Suppose someone has entered 6 as input, then the output will be

0, 1, 1, 2, 3, 5

Program:

import java.util.*;  
class Main {
     public static void main(String ...a){
        int i, k; 
        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++) { 
		    System.out.println(fibonacci(i));
	    }
    }

    static int fibonacci(int i){ 
	    if(i==0) return 0; 
	    else if(i==1) return 1; 
	    else return (fibonacci(i-1)+fibonacci(i-2));
    }

} 

Output:

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

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs