N numbers in the Fibonacci series.
Write a Java program to generate the first N numbers in the Fibonacci series ?
package Fibonacciseries;
import
java.util.Scanner;
public class
FirstNnumbersInTheFibonacciSeries
{ public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
// Ask the user for the value of N
System.out.print("Enter the
number of Fibonacci numbers to generate: ");
int n = scanner.nextInt();
// Display the Fibonacci
series
System.out.println("The first
"
+ n + " numbers
in the Fibonacci series are:");
for (int i = 0; i < n; i++)
{
System.out.print(fibonacci(i) + " ");
}
}
// Recursive method to calculate the
Nth Fibonacci
number
public static int fibonacci(int n)
{
if (n <= 1)
{
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}
Output :
Enter the number of
Fibonacci numbers to generate: 10
The first 10
numbers in the Fibonacci series are:
0 1 1 2 3 5 8 13 21
34
Explanation :
1. The main method remains the same as in the previous program, where we ask the user to input the value of N and then display the first N numbers in the Fibonacci series.2. The key difference in this alternative approach is the fibonacci method. Instead of using a loop to generate the series iteratively, this method uses recursion to calculate the Nth Fibonacci number.
3. In the fibonacci method, we check if n is less than or equal to 1. If n is 0 or 1, it means we have reached the base case of the Fibonacci series, and we return n.
4. If n is greater than 1, it means we need to calculate the Nth Fibonacci number using recursion. We do this by calling the fibonacci method recursively with n - 1 and n - 2 as arguments and then adding their results together.
5. The recursion continues until it reaches the base case (n becomes 0 or 1), and then it starts unwinding, adding up the results to calculate the desired Fibonacci number.
Comments
Post a Comment