-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNFibo.java
39 lines (28 loc) · 896 Bytes
/
NFibo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/* Write a program to print first 'n' terms of a Fibonacci series, take
the value of 'n' from user */
import java.util.Scanner;
class NFibo{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of terms in the Fibonacci series: ");
int n = sc.nextInt();
System.out.println("The Fibonacci series:");
// Print the first 'n' terms of the Fibonacci series
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if (n <= 1) {
return n;
}
int prev = 0;
int curr = 1;
for (int i = 2; i <= n; i++) {
int next = prev + curr;
prev = curr;
curr = next;
}
return curr;
}
}