Which is the best way to Print Fibonacci Series in Java?

I was going through with a lot of articles on this topic and found out there are 4 methods that can be used to print Fibonacci Series,

1. Using For Loop
2. Using While Loop
3. Using Recursion
4. Recursion with Memoization

Now the question is, which is the one most used and why? Should I use all of them or does it depend on the problem?

My All-Time Fav Resources:

1. WikiPedia
2. Scaler Topics

Thanks!
 
for-loop is good, because you can say, how many steps you want.

Whatever you do, create one specialized method that creates a new line out of your previous one. And for the sake of modern datatypes, use a list of Integers and not a friggin Array (of course it also works with an array, but lots of people can't handle them. Also there are many useful methods for Collections).
Java:
      var lines = new ArrayList<List<Integer>>();
      if (nLines >= 1) {
        lines.add(Arrays.asList(1));
        for (int i = 1; i < nLines; i++) {
          lines.add(createNewLine(lines.get(i - 1)));
        }
      }
edit: added dadtatype for main list
 
Zuletzt bearbeitet:
Es hängt von der Aufgabenstellung ab.

Eine For-Schleife nehme ich, wenn ich die ersten n Elemente der Fibonacci-Reihe ausgeben soll.

Eine While-Schleife nehme ich, wenn ich alle Elemente kleiner als eine gegebene Grenze ausgeben will.

Eine Rekursion nehme ich hier, wenn ich jemanden die Rekursion an einem einfachen Beispiel erklären will.

Eine Rekursion mit Memoisierung würde ich ebenfalls nur verwenden, wenn ich dafür ein Beispiel brauche.
Die Berechnung der Fibonacci-Reihe kann sehr leicht iterativ geschehen.
Eine Optimierung mittels Memoisierung macht eine rekursive Lösung hier nur unnötig kompliziert.

Bei komplexeren rekursiven Formeln kann die Sache natürlich anders aussehen.
 

Zurück
Oben