Fibonacci Series is a series of numbers in which each number is sum of the two preceding numbers. Number in Fibonacci Series is called Fibonacci number. First two number of series are 0 and 1.
For example:
0 , 1, 1, 2, 3, 5, 8 ......
So in above series - Third number i.e 1 = 0 + 1 (sum of two preceding number)
Fourth number i.e 2 = 1+1 (sum of two preceding number)
Fifth number i.e 3 = 1+2 (sum of two preceding number)
and so on ....
How to create Fibonacci Series program in Java?
We can create Fibonacci series in Java using -
- Programming Loops (iteration)
- Using recursion function
Using Programming Loop:
Here is a sample program to print Fibonacci series in Java. This program will print first 10 number of Fibonacci series.
package com.techiepappu.java;
/**
* This Program will print Fibonacci series using loop.
* @author http://techiepappu.blogspot.com
*/
public class FibonacciSeries1 {
public static void main(String args[]) {
int a = 0, b = 1, c, i, max = 10;
// printing first 2 number in series (i.e 0 and 1)
System.out.print(a + ", " + b);
// using java for loop for printing rest of numbers in series.
for (i = 2; i < max; ++i) {
c = a + b;
System.out.print(", " + c);
a = b;
b = c;
}
}
}
Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Using recursion function:
Recursion function is a type of function which calls itself.Every recursion should have the following characteristics.
- A base case which have solution (base value) and end the recursion.
- A way of getting problem closer to the base case.
- A recursive call.
Give below is a sample program to print Fibonacci series in Java using recursion. This program will print Fibonacci series as per user input.
package com.java.techiepappu;
import java.util.Scanner;
/**
* A sample java program to calculate and print Fibonacci series using recursion.
*
* @author http://techiepappu.blogspot.com
*/
public class FibonacciSeries2 {
public static void main(String[] args) {
int num = 0;
System.out.println("How many numbers you want to print from Fibonacci series?: ");
//using scanner class to read user input.
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
sc.close();
System.out.println("Fibonacci Series:");
while (number > num) {
System.out.println(fibonacci(num));
num++;
}
}
/**
* This is a recursive function which returns a number from fibonacci series.
* @param n
* @return nth number of fibonacci series.
*/
public static int fibonacci(int n) {
if (n == 0 || n == 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
Output: How many numbers you want to print from Fibonacci series?:
10
Fibonacci Series:
0
1
1
2
3
5
8
13
21
34
No comments :
Post a Comment