If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Fibonacci numbers are a sequence of numbers in which each number is the sum of the two preceding ones, starting from 0 and 1. The Fibonacci sequence typically starts with 0 and 1, and then each subsequent number is the sum of the previous two. The sequence looks like this:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Here's a Java program to generate the first 'n' Fibonacci numbers:
javaCopy code
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of Fibonacci numbers to generate: ");
int n = scanner.nextInt();
// Generate and print the Fibonacci series
System.out.println("Fibonacci Series:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
scanner.close();
}
// Function to calculate the nth Fibonacci number
public static int fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}
Example output:
mathematicaCopy code
Enter the number of Fibonacci numbers to generate: 10
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34
In the program above, we take the user input for the number of Fibonacci numbers to generate and store it in the variable n
. We then use a for
loop to iterate from 0 to n-1
, and for each value of 'i', we call the fibonacci
function to calculate the i
-th Fibonacci number.
The fibonacci
function is a recursive function that returns the n
-th Fibonacci number. If n
is 0, the function returns 0, and if n
is 1, it returns 1. For n
greater than 1, the function recursively calls itself to calculate the sum of the previous two Fibonacci numbers.
Keep in mind that the Fibonacci sequence can grow very quickly, and the recursive approach can be inefficient for large values of n
. For better performance, you can use iterative methods or memoization techniques to store previously calculated Fibonacci numbers.
Comments: 0