Java

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. In mathematical terms, it is defined by the recurrence relation: F(n) = F(n-1) + F(n-2), with F(0) = 0 and F(1) = 1. The sequence typically begins as 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on, with each subsequent number being the sum of the two preceding ones.

Understanding the Code:

1.   The code initializes variables n1 and n2 with the first two numbers of the Fibonacci series, i.e., 0 and 1, respectively. It also initializes a variable next to store the next number in the series.

2.   The code starts by printing the initial two numbers of the Fibonacci series (0 and 1) as they are not generated within the loop.

3.   The main logic is implemented within a while loop that continues indefinitely (while(true)), as there's no predefined limit to the Fibonacci series. However, the loop contains a conditional statement to break out of the loop once the next number exceeds 100.

4.   Inside the loop, the next number in the Fibonacci series is calculated by adding n1 and n2.

5.   If the next number exceeds 100, the loop is terminated using a break statement.

6.   The next number in the Fibonacci series is printed.

7.   n1 is updated to the value of n2, and n2 is updated to the value of next, preparing for the next iteration.

public class FibonacciSeries {
   
    public static void main(String[] args) {
       
        int n1=0;
        int n2=1;
        int next=0;
        System.out.print("Fibonacci Series "+n1+" , "+n2);
        while (true) {
            next=n1+n2;


            if(next>100){
                break;
            }
        System.out.print(" , "+next);
        n1=n2;
        n2=next;
           
        }


    }
}

Conclusion : In conclusion, the Fibonacci series algorithm in Java presented in this code efficiently generates the Fibonacci sequence up to a specified limit. By utilizing basic arithmetic operations and looping constructs, the algorithm produces each number in the series by adding the two preceding ones.

Related Posts

Table Of Contents

;