Skip to content

Commit 1ea833d

Browse files
Added Nth Fibonacci Number program
1 parent 2cfa1d5 commit 1ea833d

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
---
2+
title: Java program To Find The Nth Fibonacci Number
3+
shotTitle: Find Nth Fibonacci Number
4+
description: This code takes the value of N from user and displays the Nth number of the Fibonacci Series.
5+
---
6+
7+
N is a variable which inputs a integer value using System.in.
8+
9+
To understand this example, you should have the knowledge of the following Java programming topics:
10+
11+
- [Java Operators](/docs/operators)
12+
- [Java Basic Input and Output](/docs/basic-input-output)
13+
- [Java `for` Loop](/docs/for-loop)
14+
15+
## To find the Nth Fibonacci number
16+
17+
A java program to find the Nth Fibonacci number.
18+
19+
20+
## Java Code
21+
22+
```java
23+
import java.util.Scanner;
24+
25+
public class Fibonacci {
26+
public static void main(String[] args) {
27+
long n, term1=0, term2=1, i, fib=1 ;
28+
Scanner sc = new Scanner(System.in) ;
29+
System.out.print("Enter the value of n: ") ;
30+
n = sc.nextInt() ;
31+
if (n == 1) {
32+
fib = term1;
33+
}
34+
else if (n == 2) {
35+
fib = term2;
36+
}
37+
else {
38+
for (i = 3 ; i <= n ; i ++)
39+
{
40+
fib = term1 + term2;
41+
term1 = term2;
42+
term2 = fib;
43+
}
44+
}
45+
System.out.println("The Nth Fibonacci Number is " + fib) ;
46+
sc.close();
47+
}
48+
}
49+
```
50+
51+
#### Output 1
52+
53+
```plaintext
54+
Enter the value of n: 69
55+
The Nth Fibonacci Number is 72723460248141
56+
```
57+
58+
#### Output 2
59+
60+
```plaintext
61+
Enter the value of n: 12
62+
The Nth Fibonacci Number is 89
63+
```

0 commit comments

Comments
 (0)