CS 11 Fall 2005 -- Lab 4


Breaking code into methods

First, we'll begin with your code from the previous lab that printed a pattern of stars. Specifically, we want to break down the code into a number of methods:

After writing these methods, the main method should be modified to call first the getPositiveInt method, and then to pass the result of that method call to printPattern in order to get the pattern to appear.

To get started on this project, you should create a lab-4 directory and then make a copy of your lab-3 code. From your home directory, the commands should be:

mkdir lab-4
cp lab-3/Triangles.java lab-4
cd lab-4

You will now be in your lab-4 directory with a copy of your Triangles.java code to modify.


Calculating Fibonacci numbers

The Fibonacci numbers are the following infinite sequence of integers:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 ...

More specifically, if the function F(n) provides the nth Fibonacci number, then:

F(0) = 0

F(1) = 1

F(n) = F(n-1) + F(n-2)

Your assignment is to write a wholly new program named Fibonacci that does the following:

  1. Calls a method getNonNegativeInt to obtain a non-negative integer k from the user. (Hint: Copy and modify your getPositiveInt method from the Triangles portion of this lab.)

  2. Calculate the kth Fibonacci number with a recursive method fib that you must write.

  3. Print the computed kth Fibonacci number for the user.

Hint: The hard part here is the fib method. Remember, don't think mechanically, think functionally -- that is, assume that when you call a method (even the one that you are writing) that it will do what it is supposed to do. Later, if your method has bugs, then you should think mechanically about how the program is running.


Submitting your work

When your work is complete, you should submit it using the cs11-submit command, like so:

cs11-submit lab-4 Triangles.java Fibonacci.java

This lab is due on Tuesday, October 18th at 11:59 pm!

Scott F. Kaplan
Last modified: Thu Oct 6 21:51:49 EDT 2005