## Problem:

How to find Fibonacci numbers in Java?

## Solution:

The following program shows two methods that find Fibonacci numbers. printAllFibo(n) just prints first n Fibonacci numbers and nthFibo(n) returns n-th number from the series:

```package com.farenda.solved;

public class JavaSolved {

// Print first n numbers in Fibonacci series:
public static void printAllFibo(int n) {
int a = 0, b = 1;
while (--n >= 0) {
System.out.println(b);
int tmp = b;
b += a;
a = tmp;
}
}

// Return n-th Fibonacci number:
public static int nthFibo(int n) {
int a = 0, b = 1;
while (--n >= 0) {
int tmp = b;
b += a;
a = tmp;
}
return a;
}

public static void main(String[] args) {
if (args.length == 1) {
int n = Integer.parseInt(args[0]);
System.out.printf("%d-th Fibonacci number: %d%n", n, nthFibo(n));
System.out.printf("First %d Fibonacci numbers:%n", n);
printAllFibo(n);
} else {
System.out.printf("Usage: %s number%n", JavaSolved.class.getSimpleName());
}
}
}
```

Note that this calculates Fibonacci numbers in an iterative way, because JVM doesn’t have TCO (Tail Call Optimization) as is found in many functional languages. Implementing it recursively would result in StackOverflowError for larger numbers!

## Result:

As always, lets compile and run it to see the results:

```\$> javac src/com/farenda/solved/*.java -d out
\$> java -cp out com.farenda.solved.JavaSolved 10
10-th Fibonacci number: 55
First 10 Fibonacci numbers:
1
1
2
3
5
8
13
21
34
55
```
Share with the World!