In this java program, you will learn how to print the Fibonacci series in java. And we are doing this by using for and while loops.
In mathematics, the Fibonacci numbers, commonly denoted Fn form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F0=0 and F1=1
And
Fn=Fn-1 + Fn-2
Examples of Fibonacci Series are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 and so on.
// Java Program to Display Fibonacci Series using For Loop
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
int number, t1 = 0, t2 = 1;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a Number: ");
number = scanner.nextInt();
scanner.close();
System.out.print("First " + number + " terms: ");
for (int i = 1; i <= number; ++i) {
System.out.print(t1 + " ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
Enter a Number: 10
First 10 terms: 0 1 1 2 3 5 8 13 21 34
// Java Program to Display Fibonacci Series using While Loop
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
int number, t1 = 0, t2 = 1, i = 1;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a Number: ");
number = scanner.nextInt();
scanner.close();
System.out.print("First " + number + " terms: ");
while (i <= number) {
System.out.print(t1 + " ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
i++;
}
}
}
Enter a Number: 10
First 10 terms: 0 1 1 2 3 5 8 13 21 34
Comments