CSharp · Console
using System;
using System.Collections.Generic;
//
//Borrow from https://www.dotnetperls.com/yield
//
public class Program
{
public static IEnumerable<int> ComputePower(int number, int exponent)
{
//
//Return the result with yield out of a loop. Func/Method does not stop on 'return'. Yield return, returns control to continue below.
//
yield return 0;
int exponentNum = 0;
int numberResult = 1;
//
// Continue loop until the exponent count is reached.
//
while (exponentNum < exponent)
{
//
// Multiply the result.
//
numberResult *= number;
exponentNum++;
//
// Return the result with yield.
//
yield return numberResult;
}
}
public static void Main()
{
//
// Compute powers of two
//
int exponent = 0; //no access to interator
foreach (int value in ComputePower(2, 17))
{
Console.WriteLine("2^" + (exponent++).ToString() +"="+ value);
}
Console.WriteLine();
}
}