The Fibonacci sequence is a series of numbers where a number is the sum of previous two numbers. Starting with 0 and 1, the sequence goes 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. Here we will write three programs to print fibonacci series 1) using for loop 2) using while loop 3) based on the number entered by user

To understand these programs, you should have the knowledge of for loop and while loop.

If you are new to java, refer this java programming tutorial to start learning from basics.

## Example 1: Program to print fibonacci series using for loop

public class JavaExample { public static void main(String[] args) { int count = 7, num1 = 0, num2 = 1; System.out.print("Fibonacci Series of "+count+" numbers:"); for (int i = 1; i <= count; ++i) { System.out.print(num1+" "); /* On each iteration, we are assigning second number * to the first number and assigning the sum of last two * numbers to the second number */ int sumOfPrevTwo = num1 + num2; num1 = num2; num2 = sumOfPrevTwo; } } }

Output:

Fibonacci Series of 7 numbers:0 1 1 2 3 5 8

## Example 2: Displaying Fibonacci Sequence using while loop

public class JavaExample { public static void main(String[] args) { int count = 7, num1 = 0, num2 = 1; System.out.print("Fibonacci Series of "+count+" numbers:"); int i=1; while(i<=count) { System.out.print(num1+" "); int sumOfPrevTwo = num1 + num2; num1 = num2; num2 = sumOfPrevTwo; i++; } } }

Output:

Fibonacci Series of 7 numbers:0 1 1 2 3 5 8

## Example 3: Program to display the fibonacci series based on the user input

This program display the sequence based on the number entered by user. For example – if user enters 10 then this program displays the series of 10 numbers.

import java.util.Scanner; public class JavaExample { public static void main(String[] args) { int count, num1 = 0, num2 = 1; System.out.println("How may numbers you want in the sequence:"); Scanner scanner = new Scanner(System.in); count = scanner.nextInt(); scanner.close(); System.out.print("Fibonacci Series of "+count+" numbers:"); int i=1; while(i<=count) { System.out.print(num1+" "); int sumOfPrevTwo = num1 + num2; num1 = num2; num2 = sumOfPrevTwo; i++; } } }

Output:

How may numbers you want in the sequence: 6 Fibonacci Series of 6 numbers:0 1 1 2 3 5

Checkout these related Java programs:

Afzal Hamdulay says

August 13, 2018 at 3:05 PMWhy we have used the value of i=1 and not i=0 and what will happen if we take i=0?

Bagaskara Wisnu Gunawan says

October 23, 2018 at 4:55 PMLet’s use example 1 as a test case. When you assign i=0 for the loop, it will then loop from 0 to 7 which is 8 times (0, 1, 2, 3, 4, 5, 6, 7), so we need to assign i=1 and the looping count is right.