What is the Fibonacci series?
Fibonacci series basically sum of the previous two numbers. For Example 0,1,1,2,3,5....etc.
There are 2 ways in java for the implementation of the Fibonacci series.
- Fibonacci Series without using recursion
- Fibonacci Series using recursion
1. Fibonacci Series in Java without using recursion
the Fibonacci series program in java without using recursion
Code
public class Fibonacci1 {
public static void main(String[] args) {
int a1=0;
int a2=1;
int a3;
int i;
int count = 10;
System.out.print(a1+" "+a2);
for(i=2;i<count;++i)
{
a3=a1+a2;
System.out.print(" "+a3);
a1=a2;
a2=a3;
}
}
}
Output
0 1 1 2 3 5 8 13 21 34
a). Fibonacci Series in Java without using recursion (With Scanner Class).
The scanner class is used for taking input from the user in java programming. Here we use the scanner class so that the user can print the Fibonacci series according to his choice.
Code
public static void main(String[] args) {
int a1=0;
int a2=1;
int a3;
int i;
Scanner t = new Scanner(System.in);
System.out.println("Enter the Number");
int count = t.nextInt();
System.out.print(a1+" "+a2);
for(i=2;i<count;++i)
{
a3=a1+a2;
System.out.print(" "+a3);
a1=a2;
a2=a3;
}
}
}
Output
Enter the Number 10
0 1 1 2 3 5 8 13 21 34
0 Comments