Finding Nth Fibonacci Number in Java
LearnCodeProfessor
Posted on March 17, 2024
In this article, we will learn how to write a Java program to find the Nth Fibonacci number. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, starting from 0 and 1. The sequence looks like this: 0, 1, 1, 2, 3, 5, 8, 13, ...
To find the Nth Fibonacci number, we can use a simple iterative approach or a recursive approach. Let's look at both approaches.
- Iterative Approach:
In this approach, we can iterate through the sequence by calculating each Fibonacci number one by one. Here's the Java program to find the Nth Fibonacci number using an iterative approach:
public class Fibonacci {
public static int findNthFibonacci(int n) {
int a = 0;
int b = 1;
int result = 0;
for (int i = 2; i <= n; i++) {
result = a + b;
a = b;
b = result;
}
return n > 0 ? b : a;
}
public static void main(String[] args) {
int n = 10;
System.out.println("The " + n + "th Fibonacci number is: " + findNthFibonacci(n));
}
}
- Recursive Approach:
In this approach, we can solve the problem recursively by defining a base case and calling the function itself for the preceding Fibonacci numbers. Here's the Java program to find the Nth Fibonacci number using a recursive approach:
public class Fibonacci {
public static int findNthFibonacci(int n) {
if (n <= 1) {
return n;
}
return findNthFibonacci(n - 1) + findNthFibonacci(n - 2);
}
public static void main(String[] args) {
int n = 10;
System.out.println("The " + n + "th Fibonacci number is: " + findNthFibonacci(n));
}
}
Both approaches will give you the Nth Fibonacci number, but the recursive approach might be slower and less efficient for large values of N due to the additional function calls.
That's it! You now know how to write a Java program to find the Nth Fibonacci number using both iterative and recursive approaches. Experiment with different values of N to see the Fibonacci sequence in action.
Posted on March 17, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.