In this Java program, I show you how to calculate the Fibonacci series of a given number in Java (using for loop).
Fibonacci series is a sequence of values such that each number is the sum of the two preceding ones, starting from 0 and 1. The beginning of the sequence is thus:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ...
Fibonacci Series Java Program Using for Loop
In this program, we are using a simple for loop to demonstrate how to calculate the Fibonacci series in Java.
package net.javaguides.corejava.programs;
import java.util.Scanner;
/**
* This program calculates the fibonacci sequence of given number.
*
* @author Ramesh Fadatare
*
*/
public class FibonacciProgramUsingLoop {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int maxNumber = scanner.nextInt();
int previousNumber = 0;
int nextNumber = 1;
System.out.print("Fibonacci Series of " + maxNumber + " numbers:");
for (int i = 1; i <= maxNumber; ++i) {
System.out.print(previousNumber + " ");
int sum = previousNumber + nextNumber;
previousNumber = nextNumber;
nextNumber = sum;
}
scanner.close();
}
}
Output:
Enter a number: 10
Fibonacci Series of 10 numbers:0 1 1 2 3 5 8 13 21 34
Fibonacci Series Java Program Using for Loop and BigInteger
Since Fibonacci series is a sequence of infinite numbers, we use BigInteger type for calculations:
package net.javaguides.corejava.programs;
import java.math.BigInteger;
import java.util.Scanner;
/**
* This program calculates the fibonacci sequence of given number.
* @author Ramesh Fadatare
*
*/
public class FibonacciProgramUsingLoop {
public static BigInteger fibonacci(int n) {
if (n <= 1) return BigInteger.valueOf(n);
BigInteger previous = BigInteger.ZERO, next = BigInteger.ONE, sum;
for (int i = 2; i <= n; i++) {
sum = previous;
previous = next;
next = sum.add(previous);
}
return next;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
BigInteger val = fibonacci(i);
System.out.print(val + "\t");
}
scanner.close();
}
}
Output:
Enter a number: 10
0 1 1 2 3 5 8 13 21 34
Related Java Programs
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Comments
Post a Comment