fibonacci java program code example

Example 1: fibonacci java

import info1.*;

public class FibonacciDemo1{

  public static void main(String[] args){

    System.out.print("Geben Sie ein Zahl an: ");

    int a = Console.in.readInt();

    System.out.println("fib("+a+") = " + fibonacci(a));

  }

  private static int fibonacci(int a){

    if (a==1||a==2) return 1;

    else return fibonacci(a-1)+fibonacci(a-2);

  }

}

Example 2: write a java program to fibonacci series

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;
        }
    }
}

Example 3: fibonacci series in java

// java program to display fibonacci series using for loop
public class FibonacciSeriesForLoop
{
   public static void main(String[] args)
   {
      int f = 10, num1 = 0, num2 = 1;
      System.out.print("First " + f + " fibonacci sequence: ");
      for(int a = 1; a <= f; ++a)
      {
         System.out.print(num1 + " + ");
         int total = num1 + num2;
         num1 = num2;
         num2 = total;
      }
   }
}

Tags:

Java Example