Java Program to Display Fibonacci Series

JavaObject Oriented ProgrammingProgramming

In this article, we will understand how to find even sum of Fibonacci series till number N. A Fibonacci series is sequence of numbers formed by the sum of its two previous integers. An even Fibonacci series is all the even numbers of the Fibonacci series.

Below is a demonstration of the same −

Fibonacci series generates the subsequent number by adding two previous numbers. Fibonacci series starts from two numbers − F0 & F1. The initial values of F0 & F1 can be taken 0, 1 or 1, 1 respectively.

Fn = Fn-1 + Fn-2

Hence, a Fibonacci series can look like this −

F8 = 0 1 1 2 3 5 8 13

or, this,

F8 = 1 1 2 3 5 8 13 21

Input

Suppose our input is −

The input : 15

Output

The desired output would be −

The fibonacci series till 15 terms:

Algorithm

Step 1 - START
Step 2 - Declare values namely
Step 3 - Read the required values from the user/ define the values
Step 4 - Use a for loop to iterate through the integers from 1 to N and assign the sum of
consequent two numbers as the current Fibonacci number
Step 5- Display the result
Step 6- Stop

Example 1

Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool run button.

import java.util.Scanner;
public class Main {
   public static void main(String[] args) {
      int my_input , term_1, term_2, term_3;
      term_1 = 0;
      term_2 = 1;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the number : ");
      my_input = my_scanner.nextInt();
      System.out.println("The fibonacci series till " + my_input + " terms:");
      for (int i = 1; i <= my_input; ++i) {
         System.out.print(term_1 + " ");
         term_3 = term_1 + term_2;
         term_1 = term_2;
         term_2 = term_3;
      }
   }
}

Output

Required packages have been imported
A reader object has been defined
Enter the number : 15
The fibonacci series till 15 terms:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Example 2

Here, the integer has been previously defined, and its value is accessed and displayed on the console.

public class Main {
   public static void main(String[] args) {
      int my_input , term_1, term_2, term_3;
      my_input = 15;
      term_1 = 0;
      term_2 = 1;
      System.out.println("The number are defined as " +my_input );
      System.out.println("The fibonacci series till " + my_input + " terms:");
      for (int i = 1; i <= my_input; ++i) {
         System.out.print(term_1 + " ");
         term_3 = term_1 + term_2;
         term_1 = term_2;
         term_2 = term_3;
      }
   }
}

Output

The number are defined as 15
The fibonacci series till 15 terms:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
raja
Updated on 21-Feb-2022 12:56:42

Advertisements