Java Program for n-th Fibonacci number

There are multiple ways in which the ‘n’thFibonacci number can be found. Here, we will use dynamic programming technique as well as optimizing the space.

Let us see an example −

Example

Live Demo

public class Demo{
static int fibo(int num){
int first = 0, second = 1, temp;
if (num == 0)
return first;
if (num == 1)
return second;
for (int i = 2; i <= num; i++){
temp = first + second;
first = second;
second = temp;
}
return second;
}
public static void main(String args[]){
int num = 7;
System.out.print("The 7th fibonacci number is : ");
System.out.println(fibo(num));
}
}

Output

The 7th fibonacci number is : 13

A class named Demo contains a function named ‘fibo’, that gives Fibonacci numbers upto a given limit. It checks if the number is 0, and if yes, it returns 0, and if the number is 1, it returns 0,1 as output. Otherwise, it iterates from 0 to the range and then adds the previous number and current number and gives that as the ‘n’th Fibonacci number. In the main function, a value for the range (upto which Fiboncacci numbers need to be generated) is defined. The function ‘fibo’ is called by passing this value. The relevant message is displayed on the console.

Published on 08-Jul-2020 10:38:54