-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFibonacciLoop.java
More file actions
38 lines (31 loc) · 976 Bytes
/
FibonacciLoop.java
File metadata and controls
38 lines (31 loc) · 976 Bytes
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
import java.util.Scanner;
public class FibonacciLoop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of terms for Fibonacci series: ");
int n = input.nextInt();
if (n < 0) {
System.out.println("Please enter a non-negative number of terms.");
return;
}
if (n == 0) {
System.out.println("Fibonacci Series: (empty)");
return;
}
if (n == 1) {
System.out.println("Fibonacci Series: 0");
return;
}
int a = 0;
int b = 1;
System.out.print("Fibonacci Series: " + a + ", " + b);
for (int i = 2; i < n; i++) {
int nextTerm = a + b;
System.out.print(", " + nextTerm);
a = b;
b = nextTerm;
}
System.out.println(); // New line at the end
input.close();
}
}