Objective: Write a program to print first n numbers in Fibonacci series.
Fibonacci number: First two Fibonacci numbers are defined as 0 and 1 and every number after the first two is the sum of the two preceding ones
Fibonacci Sequence- 0 1 1 2 3 5 8 13 21 34 55 89 ……..
Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FibonacciSeries { | |
public static void printFibonacci(int n){ | |
int one = 0; | |
int two = 1; | |
System.out.println("First " + n + " elements in fibonacci series are: "); | |
for (int i = 0; i <n ; i++) { | |
System.out.print(one + " "); | |
int temp = one + two; | |
one = two; | |
two = temp; | |
} | |
} | |
public static void main(String[] args) { | |
int n = 10; | |
printFibonacci(n); | |
} | |
} |
Output:
First 10 elements in fibonacci series are: 0 1 1 2 3 5 8 13 21 34