JAVA program to find fibonacci series upto n

JAVA program to find fibonacci series upto n

This JAVA program is to find fibonacci series upto a given range. Fibonacci series is a series in which each number is the sum of preceding two numbers.

For example, fibonacci series upto n=7 will be 0,1,1,2,3,5.

Logic

We use a while loop and keep going till we generate first n terms.We store the second term inside the first term, the third term inside the second and add the first two terms.

Dry Run of the Program

Take input ‘n’.Let us take n=5

1st iteration while(c<=n;)   i.e. while(0<=5)

print(c)  OUTPUT:- 0

a=b;  i.e. a=1;

b=c;  i.e. b=0;

c=a+b; i.e. c=1;

2nd iteration while(c<=n;)   i.e. while(1<=5)

print(c)  OUTPUT:- 0 1 

a=b;  i.e. a=0;

b=c;  i.e. b=1;

c=a+b; i.e. c=1;

3rd iteration while(c<=n;)   i.e. while(1<=5)

print(c)  OUTPUT:- 0 1 1

a=b;  i.e. a=1;

b=c;  i.e. b=1;

c=a+b; i.e. c=2;

4th iteration while(c<=n;)   i.e. while(2<=5)

print(c)  OUTPUT:- 0 1 1 2

a=b;  i.e. a=1;

b=c;  i.e. b=2;

c=a+b; i.e. c=3;

5th iteration while(c<=n;)   i.e. while(3<=5)

print(c)  OUTPUT:- 0 1 1 2 3

a=b;  i.e. a=2;

b=c;  i.e. b=3;

c=a+b; i.e. c=5;

6th iteration while(c<=n;)   i.e. while(5<=5)

print(c)  OUTPUT:- 0 1 1 2 3 5

a=b;  i.e. a=3;

b=c;  i.e. b=5;

c=a+b; i.e. c=8;

While Loop ends here as c=8 which is not less than or equal to n(5).

Program

import java.util.*;

class fiboN
{
	public static void main(String args[])
	{
	        int i,c=0,n;
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter a number to generate fibonacci series upto nth term");
    		n=sc.nextInt();
  		int a=0;
   		int b=1;
		
		System.out.println("Fibonacci series upto "+n+" is :-");
   		while(c<=n)
   		{
       			System.out.print(c+" ");
       			a=b;
       			b=c;
       			c=a+b;
   		}
	}
}

Output

Share Me!