This program generates the Fibonacci sequence up to a given number. The sequence is generated recursively using a method called fibonacci().
First, the program prompts the user to enter the total number of Fibonacci numbers to generate. Then, it initializes two variables a and b to 0 and 1 respectively, and prints the first two Fibonacci numbers. The method fibonacci() takes three arguments a, b, and n. a and b represent the last two Fibonacci numbers generated, and n represents the number of Fibonacci numbers yet to be generated.
In each recursive call of fibonacci(), the sum of the last two numbers is calculated and printed. Then, the value of a is set to the current value of b, and b is set to the sum. This way, the last two numbers are updated for the next recursive call. The recursion continues until all the required Fibonacci numbers have been printed.
Overall, this program generates the Fibonacci sequence recursively and demonstrates how recursion can be used to solve a problem that involves repetitive calculations.
import java.util.*; public class Fibonacci { public static void main(String[] args) { Scanner input = new Scanner(System.in); int a = 0,b = 1,n; System.out.printf("Enter Total number of Fibonacci : "); n = input.nextInt(); System.out.printf("Fibonacci series.. "); System.out.printf("\n%d\n%d ", a, b); fibonacci(a, b, n - 2); } public static void fibonacci(int a, int b, int n) { int sum; if (n > 0) { sum = a + b; System.out.printf("\n%d ", sum); a = b; b = sum; fibonacci(a, b, n - 1); } } }
Enter Total number of Fibonacci : 10 Fibonacci series.. 0 1 1 2 3 5 8 13 21 34
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions