How to use yield to return multiple elements from a function one at a time in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

public class Program
{
    public static IEnumerable<int> Get_Fibonacci_Sequence(int total) {
        int returnValue = 1, prev = 0;

        for (int i = 0; i < total; i++) {
            yield return returnValue;

            int temp = returnValue;
            returnValue = prev + returnValue;
            prev = temp;
        }
    }
    public static void Main()
    {
        foreach (int i in Get_Fibonacci_Sequence(11)) {
            Console.Write("{0} ", i);
        }
    }
}




/*
run:

1 1 2 3 5 8 13 21 34 55 89 

*/

 



answered Aug 3, 2022 by avibootz

Related questions

1 answer 185 views
3 answers 137 views
137 views asked Nov 12, 2024 by avibootz
1 answer 144 views
1 answer 202 views
...