Written by Sai Sameera Thota on May 18, 2013 in Java > Programming

# Java program to Print nth value in the Fibonacci sequence

The Fibonacci sequence is defined by the following rule:

The first two values in the fibonacci sequence are 0 and 1.

Every subsequent value is the sum of the two values preceding it.

import java.io.*;
class Fibonacci
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter the value of n : ");
int n = Integer.parseInt(br.readLine());
long previous = 0, result = 1;
if (n == 1)
{
System.out.print("First value in fibonacci series is 0");
}
else
{
for (long i = 0; i < n - 2; i++)
{
long sum = result + previous;
previous = result;
result = sum;
}
}
System.out.println("\n"+n+"th value in fibonacci series is : "+result);
}
}

Output:

*Related*

Sai Sameera has written **36** articles for us.

{ 0 comments… add one now }