-
Notifications
You must be signed in to change notification settings - Fork 153
/
Fibonacci.java
34 lines (29 loc) · 938 Bytes
/
Fibonacci.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
/**
* @author MadhavBahl
* @date 07/01/2018
*/
import java.util.Scanner;
public class Fibonacci {
public static int fibonacci (int num) {
if (num <= 2)
return 1;
else
return fibonacci (num-1) + fibonacci (num-2);
}
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("/* ===== Fibonacci Using Recursion ===== */");
System.out.print("\nEnter a number: ");
int n = input.nextInt();
// Print the nth element in the sequence
System.out.println("\nThe " + n + "th element in fibonacci series is: " + fibonacci(n));
// Print the sequence
System.out.print("The sequence is: ");
for (int i=1; i<=n; i++) {
if (i<n)
System.out.print(fibonacci(i) + ", ");
else
System.out.print(fibonacci(i));
}
}
}