Fibonacci Series

Java program to Print a Fibonacci Series using for, while, do-while, method and recursion.

There are different ways to Print a Fibonacci Series in Java.
  1.          Fibonacci Series using For Loop
  2.          Fibonacci Series using While Loop
  3.          Fibonacci Series using Do-While Loop
  4.          Fibonacci Series using Method
  5.          Fibonacci Series using Recursion

import java.util.*;
public class FibonacciSeries 
{
	public static void main(String[] args) 
	{
		int a=0,b=1,c;
		Scanner s = new Scanner(System.in);
		System.out.println("\n Enter Limit...");
		int size = s.nextInt();
		System.out.print("\n"+ a +" "+ b);
		for(int i=0; i<size; i++)
		{
			c=a+b;
			a=b;
			b=c;
			System.out.print(" " + c);
		}		
	}
}

Output:

Enter Limit...
10

0 1 1 2 3 5 8 13 21 34 55




public class fibUsingWhile 
{
	public static void main(String[] args) 
	{
		int a=0,b=1,c,i=0;
		System.out.print("\n"+ a +" "+ b);
		while( i<5 )
		{
			c=a+b;
			a=b;
			b=c;
			System.out.print(" " + c);
			i++;
		}		
	}
}

Output:

0 1 1 2 3 5 8



public class fibDoWhile 
{
	public static void main(String[] args) 
	{
		int a=0,b=1,c,i=0;
		System.out.print("\n"+ a +" "+ b);
		do
		{
			c=a+b;
			a=b;
			b=c;
			System.out.print(" " + c);
			i++;
		}while( i<5 );
	}
}

Output:

0 1 1 2 3 5 8



public class FibMethod 
{
	void fib()
	{
		int a=0,b=1,c;
		System.out.print("\n"+ a +" "+ b);
		for(int i=0; i<5; i++)
		{
			c=a+b;
			a=b;
			b=c;
			System.out.print(" " + c);
		}
	}
	public static void main(String[] args) 
	{
		FibMethod obj = new FibMethod();
		obj.fib();
	}
}

Output:

0 1 1 2 3 5 8

import java.util.*;
public class FibRecursion {
	int fibSeries(int n){
		if(n<=1) 
		{
			return n; 
		}
		return fibSeries(n-1)+fibSeries(n-2);
	}
	public static void main(String[] args) 
	{
		Scanner scan = new Scanner(System.in);
		System.out.println("\n Enter Limit...");
		int N = scan.nextInt();
		FibRecursion f = new FibRecursion();
		f.fibSeries(N);
		for(int i=0; i<N; i++)
		{
			System.out.print(" " + f.fibSeries(i));
		}		
	}
}

Output:

Enter Limit...
10
 0 1 1 2 3 5 8 13 21 34



No comments:

Post a Comment

If you have any doubts, please let me know

Pattern 31 & 32