Algorithm


  1. Start
  2. Initialize variables n (number of terms) and first and second as 0 and 1 respectively.
  3. Print the first and second terms (first and second).
  4. Use a loop to generate the Fibonacci series: a. Loop from 3 to n. b. Calculate the next term next as the sum of first and second. c. Print next. d. Update first to the value of second. e. Update second to the value of next.
  5. End

 

Code Examples

#1 Code Example- Display Fibonacci Series Using for Loop

Code - Java Programming

class Main {
  public static void main(String[] args) {

    int n = 10, firstTerm = 0, secondTerm = 1;
    System.out.println("Fibonacci Series till " + n + " terms:");

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

      // compute the next term
      int nextTerm = firstTerm + secondTerm;
      firstTerm = secondTerm;
      secondTerm = nextTerm;
    }
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Fibonacci Series till 10 terms:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
Advertisements

Demonstration


Java Programing Example to Display Fibonacci Series-DevsEnv