logo Practice-It logo

FibonacciIterator

Language/Type: Java collections Iterator
Author: Marty Stepp (on 2013/01/29)

Write a class named FibonacciIterator that would be usable as a stand-alone class to implement an iterator over the Fibonacci integers. Recall that the first two Fibonacci numbers are 0 and 1, and each following Fibonacci number is the sum of the prior two. The first several Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

FibonacciIterator itr = new FibonacciIterator();
while (itr.hasNext()) {
    System.out.print(itr.next() + " ");   // 0 1 1 2 3 5 8 13 21 34 55 89 144 233 ...
}

Implement the hasNext and next operations; when the remove method is called, you can throw an UnsupportedOperationException. The Fibonacci numbers are an infinite sequence, so your hasNext method can always return true. Your iterator should not construct any internal data structures.

Type your solution here:


This is a class problem. Submit a complete Java class as described.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.