# Thinking in Java Fourth Edition Bruce Eckel Chapter 3 Exercise 9

Exercise 9: A Fibonacci sequence is the sequence of numbers 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on, where each number (from the third on) is the sum of the previous two. Create a method that takes an integer as an argument and displays that many Fibonacci numbers starting from the beginning, e.g., If you run java Fibonacci 5 (where Fibonacci is the name of the class) the output will be: 1, 1, 2, 3, 5.

public class Fibonacci
{
int fib(int n)
{
if(n < 2) return 1;
return (fib(n - 2) + fib(n - 1));
}
public static void main(String[] args)
{
Fibonacci f = new Fibonacci();
int k = Integer.parseInt(args);
System.out.println("First " + k + " Fibonacci number(s): ");
for(int i = 0; i < k; i++)
System.out.println(f.fib(i));
}
}

Output:

## 4 Replies to “Thinking in Java Fourth Edition Bruce Eckel Chapter 3 Exercise 9”

1.  hack exp says:

I enjoy, result in I found exactly what I was taking a look for. You have ended my four day lengthy hunt! God Bless you man. Have a great day. Bye

2.  Fedorek says:

I consider something really special in this site.

3.  chry says:

Your site has proven useful to me.

4.  Haywood Gaffke says:

I’m grateful for having you as a friend!