🔢 Purpose of the Program
This program prints Fibonacci numbers that are less than 89.
🧠 Understanding the Code
public class Fibonacci {
This defines a public class named Fibonacci
.
public static void main(String[] args) {
This is the main method—where the program starts execution.
int f = -1;
int s = 1;
int t = 0;
These are integer variables:
-
f
is initialized to -1 -
s
is initialized to 1 -
t
is initialized to 0
These will be used to calculate Fibonacci numbers.
Note: Fibonacci starts with 0, 1, 1, 2, 3, 5...
Usingf = -1
ands = 1
makes the first sum0
(-1 + 1
).
while(t < 89){
Loop continues as long as the current number (t
) is less than 89.
t = f + s;
Calculate the next number in the Fibonacci sequence.
System.out.println(t);
Print the current Fibonacci number.
f = s;
s = t;
Update variables to prepare for the next Fibonacci number:
-
f
becomes the olds
-
s
becomes the newt
📌 Sample Output
This prints:
0
1
2
3
5
8
13
21
34
55
89
Even though the condition is
t < 89
, it still prints 89, because the condition is checked aftert
is calculated and printed.
✅ Summary
This is a simple and clever way to generate Fibonacci numbers using just a while
loop and 3 variables. It avoids arrays or recursion.
Would you like the same program using recursion or with user input for the limit?