Fibonacci Series
The Fibonacci series is a series where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Program to print fibonacci series using for loop
public class Fibonacci {
public static void main(String[] args) {
int n = 10, num1 = 0, num2 = 1;
System.out.print("First " + n + " terms: ");
for (int i = 1; i <= n; ++i)
{
System.out.print(num1 + " ");
int sum = num1 + num2;
num1 = num2;
num2 = sum;
}
}
}
Output
0 1 1 2 3 5 8
Fibonacci series up to a given number (instead of terms)
public class Fibonacci {
public static void main(String[] args) {
int n = 100, t1 = 0, t2 = 1;
System.out.print("Upto " + n + ": ");
while (t1 <= n)
{
System.out.print(t1 + " + ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
Output
Upto 100: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 89 +