-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathE09Fibonacci.java
More file actions
36 lines (32 loc) · 1.25 KB
/
Copy pathE09Fibonacci.java
File metadata and controls
36 lines (32 loc) · 1.25 KB
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
//: D:/Code/Source/Java/Think in Java 4th/Chapter_4/E09Fibonacci.java
//: {Args: 20}
/****************** Exercise 9 **********************
* A Fibonacci sequence is the sequence of numbers 1,
* 1, 2, 3, 5, 8, 13, 21, 34, etc., where each number
* (from the third on) is the sum of the previous
* two. Create a method that thakes an integer as an
* argument and displays that many Fibonacci numbers
* starting from the beginning. if, e.g., you run java
* Fibonacci 5 (where Fibonacci is the name of the
* class) the output will be: 1, 1, 2, 3, 5.
****************************************************/
//package Chapter_4;
public class E09Fibonacci{
static int fib(int n){
if(n <= 2)
return 1;
return fib(n-1) + fib(n - 2);
}
public static void main(String[] args){
//Get the max value from the command line:
int n = Integer.parseInt(args[0]);
if(n < 0){
System.out.println("Cannot use negative numbers");
return;
}
for(int i = 1; i <= n; i++)
System.out.println(fib(i) + ", ");
}
}/* Output:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765,
*///:~