Fibonacci series program in Java

In this section you will learn how to make Fibonacci series program using loop in Java. Just simple mathematic operation we will perform to make the Fibonacci series program. In this program we are taking the input from user and assigning some default value to few variables.

What is Fibonacci series or number?

A series of number in which each number is sum of previous two numbers. The Fibonacci series number is given below.

Example of fibonacci series:

0, 1, 1, 2, 3, 5, 8, 13, upto n series.

0+1 =1, 1+1=2, 1+2=3, 3+5=8, 5+8=13.....

What is scanner function?

Scanner function is use to take the input from user in java.

How program will work?

Program of fibonacci series in Java.


	import java.util.Scanner;

	class Fibonacci
	{
		public static void main(String arg[])
		{
			int i=1, n, f1 = 0, f2 = 1, f3;
			Scanner sc = new Scanner(System.in);
			System.out.println("ENTER A NUMBER:-");
			n = sc.nextInt();
			System.out.print(f1+" "+f2);
			do
			{
				f3=f1+f2;
				System.out.print(" "+f3);
				f1=f2;
				f2=f3;
				i++;
			}
			while(i<=n-1);
		}
	}

Output:


	ENTER A NUMBER:- 10
	0 1 1 2 3 5 8 13 21 34 55

Advertisment

Post Your Comment