JAVA PROGRAM TO DEMONSTRATE THE FIBONACCI SEQUENCE (UPTO 11 NUMBERS):-




 


///JAVA PROGRAM TO DEMONSTRATE THE FIBONACCI SEQUENCE (UPTO 11 NUMBERS):-

public class Main {
    public static void main(String[] args) {
        int num = 10;  // Set the number of Fibonacci numbers you want to generate
       
        // Loop to generate and print the first 11 Fibonacci numbers
        for (int i = 0; i <= num; i++) {
            int fiboNumber = fibo(i);  // Call the fibo() method to calculate the Fibonacci number
            System.out.println(fiboNumber);  // Print the calculated Fibonacci number
        }
    }

    // Recursive method to calculate the nth Fibonacci number
    static int fibo(int num) {
        // Base case: If num is 0 or 1, return num as the Fibonacci number
        if (num <= 1) {
            return num;  // Base case: fibo(0) = 0, fibo(1) = 1
        } else {
            // Recursive case: Calculate the nth Fibonacci number by adding the (n-1)th and (n-2)th Fibonacci numbers
            return fibo(num - 1) + fibo(num - 2);
        }
    }
}

  1. Inside the main method: The variable num is initialized to 10, which indicates that you want to generate the first 11 Fibonacci numbers (from Fibonacci 0 to Fibonacci 10). 
  2. A for loop is used to iterate from 0 to num (inclusive). During each iteration, it calculates and prints the Fibonacci number for the current index. 
  3. The fibo method: This is a recursive method that calculates the Fibonacci number for a given index num. 
  4. The base case checks if num is 0 or 1.
  5.  If so, it returns num itself as the Fibonacci number because fibo(0) is 0 and fibo(1) is 1.
  6.  If num is greater than 1, it enters the recursive case. It calculates the Fibonacci number for num by summing up the (n-1)th and (n-2)th Fibonacci numbers using recursive calls to fibo(num - 1) and fibo(num - 2). 
  7. The code generates and prints the first 11 Fibonacci numbers using recursion and the given base cases. 
  8. The Fibonacci sequence is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1.



Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.