-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02.txt
68 lines (57 loc) · 3.44 KB
/
02.txt
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.Scanner;
public class FibonacciSeries {
// Recursive function to calculate Fibonacci series
public static int recursiveFibonacci(int n) {
if (n <= 1)
return n;
return recursiveFibonacci(n - 1) + recursiveFibonacci(n - 2);
}
// Non-recursive function to calculate Fibonacci series
public static void nonRecursiveFibonacci(int n) {
int first = 0, second = 1;
System.out.println("Fibonacci Series (Non-Recursive):");
for (int i = 0; i < n; ++i) {
System.out.print(first + " ");
int next = first + second;
first = second;
second = next;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.print("Enter the number of terms in the Fibonacci series: ");
int numTerms = scanner.nextInt();
System.out.println("\nMenu:");
System.out.println("1. Generate Fibonacci Series (Recursive)");
System.out.println("2. Generate Fibonacci Series (Non-Recursive)");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Fibonacci Series (Recursive):");
for (int i = 0; i < numTerms; ++i) {
System.out.print(recursiveFibonacci(i) + " ");
}
break;
case 2:
System.out.println("Fibonacci Series (Non-Recursive):");
nonRecursiveFibonacci(numTerms);
break;
case 3:
System.out.println("Exiting... Thank you!");
break;
default:
System.out.println("Invalid choice! Please enter a valid option.");
break;
}
if (choice != 3) {
System.out.print("\nDo you want to continue? (1 - Yes, 0 - No): ");
choice = scanner.nextInt();
}
} while (choice == 1);
scanner.close();
}
}