๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

WAP to print Fibonacci series in Java  


What is Fibonacci series ?
  • Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones.
  • It starts with 0 and 1.
  • The series looks like: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...
Logical Steps:
  • Initialize two variables no1 = 0 and no2 = 1.
  • Print no1 and no2.
  • Use a loop to generate the next numbers by adding no1 + no2.
  • Assign no1 = no2 and no2 = sum in each iteration.
  • Repeat for the desired number of terms.
Programs:
  • Below is the simple program:
    public class FibonacciSeries
    {
        public static void main(String[] args)
        {
            int n = 10;  // Number of terms to print
            int no1 = 0, no2 = 1;
    
            System.out.print("Fibonacci Series: " + no1 + ", " + no2);
    
            for (int i = 2; i < n; i++)
            {
                int sum = no1 + no2;
                System.out.print(", " + sum);
                no1 = no2;
                no2 = sum;
            }
        }
    }
    Output:
    Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Program Explanation:
  • Initialization and Variables:
    • Two variables no1 = 0 and no2 = 1 are initialized to store the first two numbers of the Fibonacci series.
  • Display First Two Numbers:
    • The program starts by printing the first two numbers, 0 and 1.
  • Iteration and Calculation:
    • A loop runs from 2 to n (the number of terms). In each iteration:
      • Calculate the next number as sum = no1 + no2.
      • Print the new number.
      • Update no1 to no2 and no2 to sum for the next iteration.
  • Repeat and Complete:
    • The loop continues until all n terms are printed.