fibonacci series in java using re code example

Example 1: fibonacci series in java

// fibonacci series in java using while loop
public class FibonacciSeriesWhileLoop
{
   public static void main(String[] args)
   {
      int a = 1, num = 15, num1 = 0, num2 = 1;
      System.out.print("First " + num + " fibonacci sequence: ");
      while(a <= num)
      {
         System.out.print(num1 + " , ");
         int total = num1 + num2;
         num1 = num2;
         num2 = total;
         a++;
      }
   }
}

Example 2: fibonacci series java

// 1 2 3 5 8 13 21 34

public class Fibonacci {

    public static void main(String[] args) {

        int n = 10, t1 = 0, t2 = 1;
        System.out.print("First " + n + " terms: ");

        for (int i = 1; i <= n; ++i)
        {
            System.out.print(t1 + " + ");

            int sum = t1 + t2;
            t1 = t2;
            t2 = sum;
        }
    }
}

Tags:

Java Example