Fibonacci List
Different methods to print out Fibonacci Sequence
import javax.swing.JOptionPane;
public class FiboFor {
public static void main(String[] args) {
String inpStr = JOptionPane.showInputDialog("Give the amount of Fibo numbers that you would like to print");
int inpNum = Integer.parseInt(inpStr);
int first = 0;
int second = 1;
for (int i = 1; i <= inpNum; i++) {
System.out.print(first + " ");
int nextNum = first + second;
first = second;
second = nextNum;
}
}
}
FiboFor.main(null);
import javax.swing.JOptionPane;
public class FiboWhile {
public static void main(String[] args) {
int start = 0;
String inpStr = JOptionPane.showInputDialog("Give the amount of Fibo numbers that you would like to print");
int inpNum = Integer.parseInt(inpStr);
int first = 0;
int second = 1;
while (start < inpNum) {
System.out.print(first + " ");
int nextNum = first + second;
first = second;
second = nextNum;
start++;
}
}
}
FiboWhile.main(null);
import javax.swing.JOptionPane;
public class FiboRec{
public static int Recursion(int n){
if(n == 0){
return 0;
}
if(n == 1 || n == 2){
return 1;
}
return Recursion(n-2) + Recursion(n-1);
}
public static void main(String args[]) {
String num = JOptionPane.showInputDialog("Give the amount of Fibo numbers that you would like to print");
int end = Integer.parseInt(num);
for(int i = 0; i < end; i++){
System.out.print(Recursion(i) +" ");
}
}
}
FiboRec.main(null);
abstract class Fibonacci {
abstract void run();
private int first;
private int second;
public void setFirst(int num) {
first = num;
}
public int getFirst() {
return first;
}
public void setSecond(int num) {
second = num;
}
public int getSecond() {
return second;
}
}
class Fibo extends Fibonacci {
void run() {
String inpStr = JOptionPane.showInputDialog("Give the amount of Fibo numbers that you would like to print");
int inpNum = Integer.parseInt(inpStr);
setFirst(0);
setSecond(1);
for (int i = 1; i <= inpNum; i++) {
System.out.print(getFirst() + " ");
int nextNum = getFirst() + getSecond();
setFirst(getSecond());
setSecond(nextNum);
}
}
public static void main(String args[]) {
Fibonacci obj = new Fibo();
obj.run();
}
}
Fibo.main(null);