CPSC 124 Introduction to Programming Spring 2007

Lab 6: More on Arrays and a Little on Methods

Setup

Create a lab06 directory in your cs124 directory to hold the files for this lab.

Copy the files from /classes/s07/cs124/labs/lab06/ to your lab06 directory.

Exercises

Here are the exercises for this week's lab, due next week.

  1. In mathematics, a Fibonacci number is defined as follows:

    F(n) = 0 if n = 0
    1 if n = 1
    F(n-1) + F(n-2) if n > 1

    That is, after two starting values, each number is the sum of the two preceding numbers. The first 10 Fibonacci numbers are:

    0, 1, 1, 2, 3, 5, 8, 13, 21, 34
    

    Using an array (which I'll call fib[]), we can compute the first n Fibonacci numbers. The ith element in fib[] represents the ith Fibonacci number. We start off by initializing fib[0] to 0 and fib[1] to 1, and then loop over the remaining elements setting them to fib[i-1] + fib[i-2].

    Write a program called Fib.java that prints the first n Fibonacci numbers. It should read n from the user and make sure that n is non-negative. Run your program and enter 100 for n. What happens at the higher Fibonacci numbers? Why does this happen? Put your answers to these questions in the comments at the top of Fib.java.

  2. In this exercise you will add a method for computing a die roll to the Craps program from lab 4. You will edit the provided program Craps.java and add a method called rollDie() for computing a random integer between 1 and 6. You should replace all code in the program that computes a die roll with a call to your new method. Make sure you comment your new method.

Handin

Verify that your lab06 folder contains all of the files you created or modified for this lab, then copy your entire lab06 folder to the handin directory ~mcorliss/handin/124/username (where username is replaced with your username).