;

Java Program to Display Fibonacci Series

Tutorialsrack 19/04/2021 Java

In this java program, you will learn how to print the Fibonacci series in java. And we are doing this by using for and while loops.

What is the Fibonacci Series?

In mathematics, the Fibonacci numbers, commonly denoted Fn form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

F0=0 and F1=1

And

Fn=Fn-1 + Fn-2

Examples of Fibonacci Series are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 and so on.

Example 1: Java Program to Display Fibonacci Series using For Loop

Example 1: Java Program to Display Fibonacci Series using For Loop
``````// Java Program to Display Fibonacci Series using For Loop

import java.util.Scanner;

public class JavaPrograms {

public static void main(String[] args) {

int number, t1 = 0, t2 = 1;

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a Number: ");
number = scanner.nextInt();
scanner.close();

System.out.print("First " + number + " terms: ");

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

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

Enter a Number: 10

First 10 terms: 0  1  1  2  3  5  8  13  21  34

Example 2: Java Program to Display Fibonacci Series using While Loop

Example 2: Java Program to Display Fibonacci Series using While Loop
``````// Java Program to Display Fibonacci Series using While Loop

import java.util.Scanner;

public class JavaPrograms {

public static void main(String[] args) {

int number, t1 = 0, t2 = 1, i = 1;

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a Number: ");
number = scanner.nextInt();
scanner.close();

System.out.print("First " + number + " terms: ");

while (i <= number) {
System.out.print(t1 + "  ");

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

i++;
}
}
}
``````
Output

Enter a Number: 10

First 10 terms: 0  1  1  2  3  5  8  13  21  34