roger's picture

Generating the Fibonacci sequence by using the yield keyword, non-recursively

class FibonacciSequence : IEnumerable
{
    public IEnumerator GetEnumerator()
    {
        yield return (long)0;
        yield return (long)1;

        long prev = 0;
        long curr = 1;

        for (; ; )
        {
            long next = prev + curr;
            if (next < 0)   // It overflowed. Stop.
                yield break;

            yield return next;
            prev = curr;
            curr = next;
        }
    }
}

Call it like this:

FibonacciSequence f = new FibonacciSequence(); 

foreach (long n in f)
    Console.WriteLine(n);

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <b> <br> <code> <dd> <dl> <dt> <hr> <h1> <h2> <h3> <i> <img> <li> <ol> <p> <pre> <table> <td> <th> <tr> <tt> <u> <ul>
  • Images can be added to this post.

More information about formatting options