
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements