# Fibonacci series up to n using Java

## Fibonacci series up to n using java :

Fibonacci series is a series of numbers in which each number is the sum of the two preceding numbers. For example,

0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89……….n

Where n is the maximum limit of the series.

Suppose, the value of n is 15 then the series will be,

0 , 1 , 1 , 2 , 3 , 5 , 8 ,13

In this article we will create a java program to print the above series up to n numbers. ### Working :

Step 1 : Ask the user to enter the value of n and store it in variable lim.

Step 2 : Use a condition to check the limit entered by the user is greater than 0 or not. If this condition gets true than follow the next Step, otherwise move to the Step 7.

Step 3 : Declare three variables, two for storing starting values of the series i.e. 0 and 1 and one for addition purpose.

Step 4 : Print the starting elements.

Step 5 : Use a loop to print series upto n integers.

Step 6 : Use a statement to perform addition on preceding numbers and print the elements till the limit entered by the user.

Step 7 : Print the statement “ Wrong Input ”.

### Code in Java

`//Java program to print fibonacci series up to n import java.util.Scanner;public class fibonacci{	public static void main(String[] args)	{		//scanner class declaration		Scanner sc = new Scanner(System.in);		//input from user		System.out.print("Enter the limit : ");						int lim = sc.nextInt();		if(lim > 0)		{			int y = 0, z = 1, s;			//display starting two numbers of series			System.out.print("Fibonacci Series : "+y+"  "+z+"  ");			//perform iterations till the limit entered by the user			while(z <= lim)			{				s=y+z;				y=z;				z=s;				//condition for forcing z that it should not be printed when its value is greater than limit				if(z <= lim)					System.out.print(z+"  ");			}		}		else			System.out.print("Wrong Input");		//closing scanner class(not compulsory, but good practice)		sc.close();														}}`

### Output :

`Enter the limit : 45Fibonacci Series : 0  1 1 2 3 5 8 13 21  34Enter the limit : -5Wrong Input` 