Answer to Monday's Rabbit Question
How did the rabbit counting go? For those who missed it Monday's programming question was concerned with Fibonacci's sequence for calculating generations of those cute furry animals.
Here's my code for displaying the first 22 numbers in the sequence:
public class Fibonacci {
public static void main(String args []){
//initialize variables to hold the sequence numbers
int firstNumber=0;
int secondNumber=1;
int sequenceNumber=0;
//we know how many times we want to loop around
//so use a for loop
for (int i=0; i<22;i++)
{
//calculate the next number in the sequence
sequenceNumber += firstNumber;
//display it on the screen
System.out.print(sequenceNumber + " ");
//update the first number and second number values
//so that the sequence continues forward next time it loops
firstNumber = secondNumber;
secondNumber = sequenceNumber;
}
}
}
And here's the output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946
10,946 pairs of rabbits!


No comments yet. Leave a Comment