Startertutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » Programming » Java » Programs » Basic » Java program to print the nth element in the Fibonacci series
Suryateja Pericherla Categories: Basic. No Comments on Java program to print the nth element in the Fibonacci series
0
(0)

In this article we will learn to implement a Java program to print the nth element in the Fibonacci series. A Java program is provided below to print the nth element in the Fibonacci series using both non-recursive and recursive methods.

 

Program is as follows:

import java.util.*;
class Fibonnaci
{
	int nFib(int n)
	{
		int a = 0, b = 1, c=0;
		if(n == 1)
		return 0;
		else if(n == 2)
		return 1;
		else
		{
			for(int i = 2; i < n; i++)
			{
				c = a+b;
				a = b;
				b = c;
			}
			return c;
		}
	}
	int rFib(int n)
	{
		if(n == 1)
		return 0;
		else if(n == 2)
		return 1;
		else
		{
			return rFib(n-1)+rFib(n-2);
		}
	}
}
class Driver
{
	public static void main(String[] args)
	{
		Fibonnaci f = new Fibonnaci();
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the value of n: ");
		int n = s.nextInt();
		System.out.println("Element using normal method is: "+f.nFib(n));
		System.out.println("Element using recursive method is: "+f.rFib(n));
	}
}

 

Input and output for the above program is as follows:

Enter the value of n:
5
Element using normal method is: 3
Element using recursive method is: 3

 

How useful was this post?

Click on a star to rate it!


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory