- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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.
- Related Articles
- Python Program for n-th Fibonacci number
- C/C++ Program for the n-th Fibonacci number?
- N-th Fibonacci number in Python Program
- C Program for n-th even number
- C Program for n-th odd number
- Java Program for check if a given number is Fibonacci number?
- Java Program to Find Even Sum of Fibonacci Series till number N
- Java program for removing n-th character from a string
- Java Program for nth multiple of a number in Fibonacci Series
- An efficient way to check whether n-th Fibonacci number is multiple of 10?
- Java program to print Fibonacci series of a given number.
- C program to find Fibonacci series for a given number
- Swift Program to Find Sum of Even Fibonacci Terms Till number N
- Fibonacci of large number in java
- Python program for removing n-th character from a string?

Advertisements