Fibonacci Using Loops
public class Fibonacci {
int firstFib = 1;
int secondFib = 1;
public void forFib(int numOfFib) {
if (numOfFib == 1) {
System.out.println("Using For Loop: 0");
} else if (numOfFib == 2) {
System.out.println("Using For Loop: 0 " + firstFib);
//}
//else if (numOfFib == 2) {
// System.out.println("Using For Loop: 0 " + firstFib + " " + secondFib);
} else if (numOfFib > 2) {
int prevFib = firstFib;
int currentFib = secondFib;
int nextFib;
System.out.print("Using For Loop: 0 " + firstFib + " " + secondFib);
for (int counter = 0; counter < numOfFib-3; counter++ ) {
nextFib = prevFib + currentFib; // prevFib, currentFib, nextFib
prevFib = currentFib;
currentFib = nextFib;
System.out.print(" " + nextFib);
}
}
}
public void whileFib(int numOfFib) {
if (numOfFib == 1) {
System.out.println("Using While Loop: 0");
} else if (numOfFib == 2) {
System.out.println("Using While Loop: 0 " + firstFib);
//} else if (numOfFib == 2) {
// System.out.println("Using While Loop: 0 " + firstFib + " " + secondFib);
} else if (numOfFib > 2) {
int prevFib = firstFib;
int currentFib = secondFib;
int nextFib;
System.out.print("Using While Loop: 0 " + firstFib + " " + secondFib);
int counter = 0;
while (counter < numOfFib-3) {
nextFib = prevFib + currentFib; // prevFib, currentFib, nextFib
prevFib = currentFib;
currentFib = nextFib;
System.out.print(" " + nextFib);
counter++;
}
}
}
public int recursiveFib(int n) {
if (n == 0) {
return 0;
} else
if (n == 1) {
return firstFib;
} else if (n == 2) {
return secondFib;
}
return recursiveFib(n-2) + recursiveFib(n-1);
}
public void printRecFib(int numOfFib){
System.out.print("Using Recursion: ");
for(int i = 0; i < numOfFib; i++){
System.out.print(recursiveFib(i) +" ");
}
}
public static void main(String[] args) {
Scanner scanFib = new Scanner(System.in);
int numOfFib = scanFib.nextInt();
Fibonacci fibseries = new Fibonacci();
fibseries.forFib(numOfFib); // For Loop
System.out.println();
fibseries.whileFib(numOfFib); // While Loop
System.out.println();
fibseries.printRecFib(numOfFib); // Recursive Loop
}
}
Fibonacci.main(null);