1. Home
  2. Computing & Technology
  3. Java
photo of Paul Leahy
Paul's Java Blog

By Paul Leahy, About.com Guide to Java

Answer to Monday's Rabbit Question

Sunday September 28, 2008

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!

Comments

No comments yet. Leave a Comment

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Discuss
Community Forum
Explore Java
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Java

©2009 About.com, a part of The New York Times Company.

All rights reserved.