Java/J2EE and SOA (346 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (17 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (343 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

How To Display Fibonacci Series In Java?

Last updated on Jun 17,2021 29.8K Views

16 / 29 Blog from Java Programs

The Fibonacci Sequence is a peculiar series of numbers named after Italian mathematician, known as Fibonacci. Starting with 0 and 1, each new number in the Fibonacci Series is simply the sum of the two before it. For example, starting with 0 and 1, the first 5 numbers in the sequence would be 0, 1, 1, 2, 3 and so on. In this article, let’s learn how to write the Fibonacci Series in Java.

You can mainly write Fibonacci Series in Java in two ways:

Let’s get started!

Fibonacci Series without using recursion 

When it comes to generating the Fibonacci Series without using recursion, there are two ways:

  1. Using ‘for’ loop
  2. Using ‘while’ loop

Method1: Java Program to write Fibonacci Series using for loop

The program below should help you on how to write a java program to generate first ‘n’ numbers in the Fibonacci Series using for loop. The logic used here is really simple. First, I have initialized the first two numbers of series. Then comes the for loop, which adds up its two immediate predecessors and prints the value. This continues until the program prints the first ‘n’ numbers in the series.

package Edureka;
import java.util.Scanner;
public class Fibonacci {
 
	public static void main(String[] args) 
	{
	
		 int n, first = 0,next = 1;
		 
		    System.out.println("Enter how may fibonnaci numbers to print");
	        Scanner scanner = new Scanner(System.in);
	        n = scanner.nextInt();
	        System.out.print("The first " + n + " Fibonacci numbers are: ");
	        System.out.print(first + " " + next);
	        for (int i = 1; i<=n-2; ++i)
	        {
	            int sum = first + next;
	            first = next;
	            next = sum;
	            System.out.print(" " + sum);
	        }
 
	}
 
}


Output:

Enter how may fibonnaci numbers to print
7
The first 7 Fibonacci numbers are: 0 1 1 2 3 5 8

Note: Condition in for loop is ‘n-2’. That’s because the program already prints ‘0’ and ‘1’ before it begins with for loop.

Method2: Java Program to write Fibonacci Series using while loop

The logic is similar to the previous method. It’s just the while loop condition that you need to be careful about. Take a look at the java code below to understand how to generate Fibonacci Series using while loop.

package Edureka;
import java.util.Scanner;
public class FibWhile {
 
	public static void main(String[] args) 
	{
	
		 int n, first = 0,next = 1;
		 
		    System.out.println("Enter how may fibonnaci numbers to print");
	        Scanner scanner = new Scanner(System.in);
	        n = scanner.nextInt();
	        System.out.print("The first " + n + " Fibonacci numbers are: ");
	        System.out.print(first + " " + next);
	        int i = 1;
	        while (i<n-1)
	        {
	            int sum = first + next;
	            first = next;
	            next = sum;
	            System.out.print(" " + sum);
	            i++;
	        }
 
	}
}

Output:

 
Enter how may fibonnaci numbers to print 
7 
The first 7 Fibonacci numbers are: 0 1 1 2 3 5 8 

Fibonacci Series using recursion 

Recursion is the basic java programming technique in which a function calls itself directly or indirectly. The corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily. Let’s see how to use recursion to print first ‘n’ numbers of the Fibonacci Series in Java. 

The program below should help you on how to write a recursive java program to generate first ‘n’ numbers in the Fibonacci Series. The logic here is quite simple to understand. First, the user gives the input and then the for loop is used to loop until the limit where each iteration will call the function fibonaccinumber(int n) which returns the Fibonacci number at position n. The Fibonacci function recursively calls itself adding the previous two Fibonacci numbers. 

package Edureka;
import java.util.Scanner;
public class FibRec {
	
	public static void main(String[] args) 
	{
	
		 int n;
		 
		    System.out.println("Enter how may fibonnaci numbers to print");
	        Scanner scanner = new Scanner(System.in);
	        n = scanner.nextInt();
	       
	        for (int i = 0; i<=n-1; ++i)
	        {
	           System.out.print(fibonaccinumber(i) + " ");
	        }
	}
	
	public static int fibonaccinumber(int n) {
		
		if(n==0)
			return 0;
		else if(n==1)
			return 1;
		else
			return fibonaccinumber(n-1) + fibonaccinumber(n-2);
		
	} 
}

Output:

 
Enter how may fibonnaci numbers to print 
7 
The first 7 Fibonacci numbers are: 0 1 1 2 3 5 8 

This brings us to the end of this ‘Fibonacci Series in Java’ article. We have learned how to programmatically print the Nth Fibonacci number using either loop statements or recursion.

If you found this article on “Fibonacci Series in Java”, check out the Java Course Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. 

Got a question for us? Please mention it in the comments section of this “Fibonacci Series in Java and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDate
Java Certification Training Course

Class Starts on 28th January,2023

28th January

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 25th February,2023

25th February

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How To Display Fibonacci Series In Java?

edureka.co