The Art and Science of Java, Chapter 4, Exercise 10, Solution
Can anyone help with the solution of the exercise 10. Here it is so far what I got. I'm not sure if it is right.
Modify the program in the preceding exercise so that instead of specifying the index of the final term, the program displays those terms in the Fibonacci sequence that are smaller than 10,000.
(I have included the preceding exercise below with code)
Exercise 10:
/* * FibonacciInverted.java * ---------------------- * This program displays the values in the Fibonacci sequence from F0 to F15. */
import acm.program.*;
public class FibonacciInverted extends ConsoleProgram{ public void run() { int n0 = 1; int n1 = 1; int n2; println("0" + "\n" + n0 + "\n" + n1); while(true) { // Loop nTimes terms n2 = n1 + n0; //The next term is the sum of the previous two terms if(n2 > N_TIMES)break; println(n2 + " "); n0 = n1; // The first previous number becomes the second previous number... n1 = n2; // ...and the current number becomes the previous number } } /*private constant*/ private final static int N_TIMES = 10000; }
Exercise 9:
Tn mathematics, there is a famous sequence of numbers called the Fibonacci sequence after the thirteenth-century Italian mathematician Leonardo Fibonacci. The first two terms in this sequence are 0 and I, and every subsequent term is the sum of the preceding two. Thus the first several terms in the Fibonacci sequence are as follows: F0=0
F1=1
F2 = I (0 + I) F3 = 2 (I + I) F4 = 3 (I + 2) F5 = 5 (2 + 3) F6 = 8 (3 + 5)
/* * FibonacciSequence.java * ---------------------- * This program displays the values in the Fibonacci sequence from F0 to F15. */
import acm.program.*;
public class FibonacciSequence extends ConsoleProgram{ public void run() { int n0 = 1; int n1 = 1; int n2; int nTimes = readInt("Enter the number of sequences: "); println("0" + "\n" + n0 + "\n" + n1); for (int i = 0; i < nTimes; i++) { // Loop nTimes terms n2 = n1 + n0; //The next term is the sum of the previous two terms println(n2 + " "); n0 = n1; // The first previous number becomes the second previous number... n1 = n2; // ...and the current number becomes the previous number } println(); } }

















