So after solving this and looking at the solution, I definitely made this complicated by trying to incorporate what I learned in Lecture 7. Should have completed this before watching all the stuff about methods! On the up side, I at least go to practice the new stuff. Here is the problem:

Here are the possible solutions:

The solution from the class makes this look pretty simple:

Here is my solution, which incorporates the creation of methods that we learned from Lecture 7. My solution is not as elegant, but it works 🙂 You can also find it on gist.

/* * This is the solution to the Section Handout #2 from the * Stanford CS106A online class */ import acm.program.*; public class FibonacciSequence extends ConsoleProgram { private static final int MAX_TERM_VALUE = 10000; public void run() { println( "This program lists the Fibonacci sequence" ); int term = 0; int i = 0; while (term < MAX_TERM_VALUE) { term = fib(i); if (term < MAX_TERM_VALUE) { println(term); } i++; } } private int fib(int n) { //Fib(0) = 0 //Fib(1) = 1 //Fib(2) = 1 (0 + 1) = fib(0) + fib(1) //Fib(3) = 2 (1 + 1) = fib(1) + fib(2) //Fib(4) = 3 (1 + 2) = fib(2) + fib(3) //Fib(5) = 5 (2 + 3) = fib(3) + fib(4) if (n==0) { return 0; } if (n==1) { return 1; } if (n>1) { return fib(n-1) + fib(n-2); } return 0; //need to include this in case someone enters in a negative # } }

Hi Natasha,

I approached this problem exactly like you that is to create a method…

However, i dont understand why under the run() method you introduced a new variable ‘term’.

why didnt you do sth like this :

public void run() {

int i = 0;

while (fibonacci(i)< MAX_TERM_VALUE ) {

println(fibonacci(i));

i++;

}

}

as for the private fibonacci method if I don't include the return 0;(for the negaive values) line, the fibonacci method becomes invalid. Any idea why?

In your method term = fibonnaci(i). I decided to store it as a variable “term”, but you can also just write “fibonnaci(i)” instead, like you did.

For the return 0 question, your method has to return something. The computer doesn’t know what to return if there is a negative number if you only cover positive numbers, so that’s why it becomes invalid.

Heres what I did (I used different var names):