Fibonacci with loops
Practice with for, while, and recursion
public class ForFibo {
public static void main(int counter) { // making class with counter as a parameter
int a = 0; // first two numbers to be added together
int b = 1;
int c; // c is going to store added value
for (int x = 0; x < counter; x++) { // starting with x = 0, looping and adding 1 to x so long as x < counter
c = a + b;
System.out.println(x + 1 + ": " + c);
a = b; // shifting a and b values up by one
b = c;
}
}
}
ForFibo.main(10);
public class WhileFibo {
public static void main(int counter) { // this time initializing x outside of loop
int a = 0;
int b = 1;
int c;
int x = 0;
System.out.println("Fibonacci While Loop");
while (x < counter) { // same procedure, using counter as target parameter for x and looping through a b and c
c = a + b;
System.out.println(x + 1 + ": " + c);
a = b;
b = c;
x++;
}
}
}
WhileFibo.main(10);
public class RecursiveFibo {
public static void main(int a, int b, int counter) { // since it's recursive the class relies on the basic 'tracker' integers
// as parameters
int c; // again using c as number storage, x as variable that gets updated to match counter
int x = 0;
if (x < counter) {
c = a + b;
System.out.println(counter + ": " + c);
a = b;
b = c;
counter--; // instead of counting up to a certain point this loop subtracts from counter until it matches x
RecursiveFibo.main(a, b, counter);
}
}
}
RecursiveFibo.main(0, 1, 10);
CB Standards
Skill 1.B:Determine code that would be used to complete code segments (ie For, While, Recursion)
- For loop:
for (int x = 0; x < counter; x++)
- While loop:
while (x < counter)
- Recursion:
Skill 4.C: Determine if two or more code segments yield equivalent results (be sure to Discuss how you know results are the same) Part of output line in oop is including the number's place in the sequence, and so we can use that to confirm that the results are the same
Skill 5.A: Describe the behavior of a given segment of program code (describe the difference in recursion versus for & while loops, perhaps add timing to determine speed) For and while are fairly similar because they both use several integer values to iterate through a loop to reach a certain number of repeats. The primary difference is that one uses the "x" integer (which is modified by adding to one for each loop) inside the loop, and the other instantiates it outside of the loop. However, recursion takes three basic integers as parameters because it depends on the initialized values to loop. Moreover, the function is called as part of a loop. The recursive function also relies on reducing the counter variable until it matches 0, because trying to count up leads to an infinite loop.