In fibonacci series, next number is the sum of previous two numbers. Fibonacci series is a series in which the next number is the sum of the previous two numbers.  A number series is said to be a Fibonacci series if the sum of the previous two numbers is the next number. We’ll look at how to write a Java programme to print the Fabanocci series in this post. The Fibonacci numbers will begin with 0. The fibonacci series’ first two numbers are 0 and 1.

Fibonacci series

The first and second numbers in the fabonacci series are 0 and 1. The third number is the sum of the first and second numbers. (0 +1 = 1). The sum of the second and third numbers yields the fourth number. ( 1 + 1 = 2 ). The show will continue indefinitely. The next number in the fabonacci series is defined as the sum of the previous two numbers.

For example the fabonacci series values are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, and so on.

0
1
1 ( 0 + 1 )
2 ( 1 + 1 )
3 ( 1 + 2 )
5 ( 2 + 3 )
8 ( 3 + 5 )
. . . . . . . .

Java Program

package in.yawin;

public class FibonacciSeries {
	public static void main(String[] args) {
		int count = 15;
		
		int first = 0;
		int second = 1;
		int temp;
		for (int i = 0; i < count; i++) {
			System.out.print(first + ", ");

			temp = first + second;
			first = second;
			second = temp;
		}
	}

}

Output

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,

Explanation

The first value in the java program above is set to 0. The second value is initially set to 1. In this Java program, a for loop is used to print the Fabanocci series. Each iteration of the for loop will print the first value.

Following the printing of the value, the third value is calculated by adding the first and second values. The third value is saved in a temporary variable on the program. The second value is now assigned to the first variable. The second variable is assigned the third value stored in the temp value. When the loop iterates again, it uses the incremented next first and second values.

In this manner, the for loop in Java will calculate and print the Fabanocci series.

In a java programme, the fabanacci series can be generated in two ways. The fabanacci series can be created using java loops such as for, while, and do while. The second method involves using recursive methods to generate the Fibonacci series. A fabanacci method is created for recursive execution. The fabanacci series is printed using this method. The count variable limits the number of values in the fabanacci series that can be printed. The values of the fabanacci series can be generated indefinitely.

Leave a Reply