Java Program to find fibonacci series of a number
Program
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the range of Fibonacci series");
int range = sc.nextInt();
if (range & lt; = 0) {
System.out.println("Cannot generate Fibonacci series");
System.exit(0);
}
int first = 0;
int second = 1;
System.out.println("Fibonacci Series:");
if (range == 1)
System.out.println(first);
else if (range & gt; = 2) {
System.out.print(first + "\t" + second);
for (int i = 0; i & lt; range - 2; i++) {
int fib = first + second;
System.out.print("\t" + fib);
first = second;
second = fib;
}
System.out.println();
}
}
}
Let’s break down your FibonacciSeries program in the same simple format as your example:
import java.util.Scanner;
: This imports theScanner
class, which allows the program to take input from the user.public class FibonacciSeries
: Every Java program starts with a class. Here, the class name isFibonacciSeries
.public static void main(String args[])
: Themain
method is the entry point for any Java program. Execution begins from here.Scanner sc = new Scanner(System.in);
: Creates aScanner
object (sc
) to read user input.
System.out.println("Enter the range of fibonacci series");
int range = sc.nextInt();
- Prompts the user to enter the range (number of Fibonacci terms).
- Reads the integer input using
sc.nextInt()
and stores it in the variablerange
.
if (range <= 0) {
System.out.println("Cannot generate fibonacci series");
System.exit(0);
}
- Checks if the input (
range
) is less than or equal to 0. - If true, prints an error message and stops execution.
int first = 0;
int second = 1;
System.out.println("Fibonacci Series:");
- Initializes the first two terms of the Fibonacci series (
first = 0
,second = 1
). - Prints a header for the Fibonacci series.
if (range == 1)
System.out.println(first);
- If the user specifies
range = 1
, the program prints only the first term (0
).
else if (range >= 2) {
System.out.print(first + "\t" + second);
}
- If the user specifies
range >= 2
, the program prints the first two terms (0
and1
).
for (int i = 0; i < range - 2; i++) {
int fib = first + second;
System.out.print("\t" + fib);
first = second;
second = fib;
}
- Calculates and prints the remaining Fibonacci terms:
- Adds the last two terms (
first + second
) to get the next term (fib
). - Updates
first
andsecond
to proceed to the next iteration. - This continues until the required
range
is covered.
- Adds the last two terms (
Execution:
- Initializes:
first = 0
,second = 1
. - Prints:
0
,1
. - Loop:
- Iteration 1:
fib = 0 + 1 = 1
, prints1
. - Iteration 2:
fib = 1 + 1 = 2
, prints2
. - Iteration 3:
fib = 1 + 2 = 3
, prints3
. - Iteration 4:
fib = 2 + 3 = 5
, prints5
. - Iteration 5:
fib = 3 + 5 = 8
, prints8
. - Iteration 6:
fib = 5 + 8 = 13
, prints13
.
- Iteration 1:
Output
Enter the range of Fibonacci series
8
Fibonacci Series:
0 1 1 2 3 5 8 13