Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Added Nth Fibonacci Number program
  • Loading branch information
suchismitacodes committed Oct 25, 2024
commit 1ea833d342ad0c0d216ec4955895bf4e4ca86bd8
63 changes: 63 additions & 0 deletions src/pages/programs/java-program-to-find-nth-fibonacci-number.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
---
title: Java program To Find The Nth Fibonacci Number
shotTitle: Find Nth Fibonacci Number
description: This code takes the value of N from user and displays the Nth number of the Fibonacci Series.
---

N is a variable which inputs a integer value using System.in.

To understand this example, you should have the knowledge of the following Java programming topics:

- [Java Operators](/docs/operators)
- [Java Basic Input and Output](/docs/basic-input-output)
- [Java `for` Loop](/docs/for-loop)

## To find the Nth Fibonacci number

A java program to find the Nth Fibonacci number.


## Java Code

```java
import java.util.Scanner;

public class Fibonacci {
public static void main(String[] args) {
long n, term1=0, term2=1, i, fib=1 ;
Scanner sc = new Scanner(System.in) ;
System.out.print("Enter the value of n: ") ;
n = sc.nextInt() ;
if (n == 1) {
fib = term1;
}
else if (n == 2) {
fib = term2;
}
else {
for (i = 3 ; i <= n ; i ++)
{
fib = term1 + term2;
term1 = term2;
term2 = fib;
}
}
System.out.println("The Nth Fibonacci Number is " + fib) ;
sc.close();
}
}
```

#### Output 1

```plaintext
Enter the value of n: 69
The Nth Fibonacci Number is 72723460248141
```

#### Output 2

```plaintext
Enter the value of n: 12
The Nth Fibonacci Number is 89
```