Fibonacci.java – solution to HandOut#2

/*
 * File: Fibonacci.java
 * ---------------------
 * This class is a blank one that you can change at will. Remember, if you change
 * the class name, you'll need to change the filename so that it matches.
 * Then you can extend GraphicsProgram, ConsoleProgram, or DialogProgram as you like.
 */

import acm.program.*;

public class Fibonacci extends ConsoleProgram {
	//constant for the 
	private static final int MAX_TERM_VALUE=1000;

	public void run() {
		println("This Program lists the Fibonacci sequence.");
		//we need three variables 
		//fibonacci 0 = 0
		int term = 0;
		
		//fibonacci(1) = 1
		int term2 = 1;
		
		//third variable to store the sum
		int term3 =0;
		
		//print the fibonacci(0) and (1)
		println(term);
		println(term2);
		
		// loop until we finish the number in the MAX_TERM_VALUE
		while (term < MAX_TERM_VALUE){
			// term2(sum) = term plus term2
			term3=term+term2;
			
			//print the sum
			println(term3);
			
			//mv the next number to term
			term=term2;
			
			// and the sum to term2
			term2=term3;
		}
	}
}

Leave a Reply