Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a Java program to print the Fibonacci series.
Fibonacci Series: A series of numbers in which each number (Fibonacci number) is the sum of the two preceding numbers. The simplest is the series 0, 1, 1, 2, 3, 5, 8, etc.
Logic: (previous, current) ==> (current, current + previous)
Here is the Java program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
package com.sample.clearurdoubt; import java.util.Scanner; public class FibonacciSeries { long previous, current; public FibonacciSeries() { this(0, 1); } public FibonacciSeries(long a, long b) { previous = a; current = b - a; } private long nextElement() { long temp = previous; previous = current; current = previous + temp; return temp; } public void printSeries(int numberofelements) { System.out.println("The Fibonacci Series starting with " + previous + " and " + current + ": "); System.out.print(nextElement()); for(int i = 0; i < numberofelements - 1; i++) { System.out.print(" " + nextElement()); } System.out.println(); } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Please enter the number of elements that to be printed in the series: "); int numberofelements = in.nextInt(); FibonacciSeries fibonacci = new FibonacciSeries(); fibonacci.printSeries(numberofelements); in.close(); } } |
Output:
Happy Learning :).
Please leave a reply in case of any queries.