-
Notifications
You must be signed in to change notification settings - Fork 29
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #121 from Billakanti-Teja/feature/fibonacci
Add fibonacci program in general coding questions package
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
package GeneralQuestions; | ||
|
||
import java.util.Scanner; | ||
|
||
//Program to find out the Nth number in the fibonacci series | ||
public class NthFibonacci { | ||
public static void main(String[] args) { | ||
Scanner sc = new Scanner(System.in); | ||
int n = sc.nextInt(); | ||
if (n < 0) { | ||
System.out.println("Invalid input! N must be a non-negative integer."); | ||
} else { | ||
System.out.println(fibo(n)); | ||
} | ||
|
||
sc.close(); | ||
} | ||
|
||
static int fibo(int n) { | ||
if(n==0||n==1)return n; | ||
int first = 0; | ||
int second = 1; | ||
int current = 0; | ||
for (int i = 2; i <= n; i++) { | ||
current = first + second; | ||
first = second; | ||
second = current; | ||
} | ||
return current; | ||
|
||
} | ||
} |