Fibonacci Series
🌀 What is the Fibonacci Series?
The Fibonacci sequence is a mathematical wonder where each number is the sum of the two preceding ones. It usually starts with 0 and 1. It’s not just a math concept—it appears everywhere in nature, from the spirals of shells to the arrangement of leaves on a stem!
The sequence looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Mathematically, it is defined by the formula:
Fn=Fn−1+Fn−2
🛠️ Step-by-Step Code Explanation
Instead of a table, here is the breakdown grouped by "Logic Blocks":
1. Setup & Input
import java.util.Scanner;Imports the utility needed to read what the user types.Scanner in = new Scanner(System.in);Creates a "listener" object namedinto capture keyboard input.int num = in.nextInt();Stores the user's chosen limit into the variablenum.
2. The Starting Seeds
int n1 = 0, n2 = 1, nn = 0;We initialize our variables.n1andn2are the first two numbers of the series.nn(next number) is a placeholder for the calculation.
3. The Logic Loop
for(int i = 1; i <= num; ++i)This loop acts as a counter. It will run exactly as many times as the value ofnum.System.out.print(n1 + ", ");Prints the current number in the sequence.
4. The "Sliding Window" Calculation
nn = n1 + n2;Adds the current two numbers together to find the next one.n1 = n2;The Shift: The old second number now becomes the first number.n2 = nn;The Update: The newly calculated number (nn) now becomes the second number.
Written by : @Varnit_Baiswar
import java.util.Scanner;
class Fibonacci_Series
{
public static void main()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a Number: ");
int num = in.nextInt();
int n1 = 0, n2 = 1, nn = 0;
System.out.println("Fibonacci Series Upto " + num + " :");
for(int i = 1;i <= num; ++i)
{
System.out.print(n1+", ");
nn = n1+n2;
n1 = n2;
n2 = nn;
}
System.out.println();
}
}