0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc
. The first two numbers of fibonacci series are 0 and 1.import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int n = input.nextInt();
int firstTerm = 0, secondTerm = 1;
System.out.print("Fibonacci series: " + firstTerm + " " + secondTerm + " ");
for (int i = 3; i <= n; i++) {
int nextTerm = firstTerm + secondTerm;
System.out.print(nextTerm + " ");
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}
Enter the number of terms: 20
Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Scanner
class. Then, we initialize two variables firstTerm
and secondTerm
to 0 and 1, respectively, which are the first two terms in the Fibonacci series.System.out.print()
.for
loop to generate the remaining terms in the series. We do this by calculating the sum of the previous two terms and storing it in a variable nextTerm
. We then print nextTerm
to the console using System.out.print()
, and update the values of firstTerm
and secondTerm
to prepare for the next iteration of the loop.System.out.println()
to print a new line to the console at the end of the program.import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int n = input.nextInt();
System.out.print("Fibonacci series: ");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
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);
}
}
}
Enter the number of terms: 20
Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Scanner
class. Then, we use a for
loop to generate each term in the series using the fibonacci()
method.fibonacci()
method is a recursive function that takes an integer argument n and returns the nth term in the Fibonacci series. If n is 0 or 1, we return the corresponding value of 0 or 1
. Otherwise, we recursively call the fibonacci()
method to calculate the sum of the previous two terms.System.out.print()
to print each term in the Fibonacci series to the console, separated by a space.