Fibonacci Series in Java Using Loop and Recursion

Here you will get program for fibonacci series in java using loop and recursion.

The series in which next term is calculated by adding previous two terms is called fibonacci series. Example: 0 1 1 2 3 5 8 13 21 34

Program for Fibonacci Series in Java Using Loop

import java.util.Scanner;

public class FibonacciSeriesJava {
	public static void main(String args[]){
		int n, first = 0, second = 1, next, i;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("How many terms?");
		n = sc.nextInt();
		
		System.out.print(first + " " + second);
		
		for(i = 2; i < n; ++i){
			next = first + second;
			first = second;
			second = next;
			
			System.out.print(" " + next);
		}
	}
}

Output

How many terms?
10
0 1 1 2 3 5 8 13 21 34

Program for Fibonacci Series in Java Using Recursion

import java.util.Scanner;

public class FibonacciSeriesJava {
	public static void main(String args[]){
		int n, first = 0, second = 1;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("How many terms?");
		n = sc.nextInt();
		
		System.out.print(first + " " + second);
		
		fibonacciSeries(first, second, n - 2);
	}
	
	static void fibonacciSeries(int first, int second, int n){
		int next;
		
		if(n > 0){
			next = first + second;
			first = second;
			second = next;
			
			System.out.print(" " + next);
			
			fibonacciSeries(first, second, n - 1);
		}
	}
}

 

Comment below if you have doubts or found anything incorrect in above program for fibonacci series in java.

Leave a Comment

Your email address will not be published. Required fields are marked *