Fibonacci series in Java

The Fibonacci sequence is a series of numbers where the next number is the sum of previous two numbers. By default the 1st and 2nd numbers be 0 and 1.
Fibonacci series:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ......

Here the 3rd number -> 0+1=1
the 4th number -> 1 + 1 =2
the 5th number -> 1+2=3 and soon

For example if we need Fibonacci series up-to n numbers 

Input: 8
Output: 0  1  1  2  3  5  8  13  21

Here we got Fibonacci series of first 8 numbers

Program:

import java.util.Scanner;

public class Fibanocci
{


public static void main(String[] args)
{

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int num1, num2, temp, y;
num1=0; num2=1;
System.out.print(num1+" "+num2+" ");

for (int i=2; i<=n; i++)
{

temp = num1+num2;
System.out.print(temp+" ");
num1 = num2;
num2 = temp
;
}
System.
out.println();
System.out.println(num2);

}
}

Post a Comment

0 Comments