Venciity

[Jumpstart C#] loops demo - Foreach

Jan 24th, 2014
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.46 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. #region Primes class
  5. public class Primes : IEnumerable<uint>
  6. {
  7.     private uint val = 1;
  8.  
  9.     public IEnumerator<uint> GetEnumerator()
  10.     {
  11.         bool isPrime;
  12.         uint maxDivider;
  13.         while (true)
  14.         {
  15.             isPrime = true;
  16.             maxDivider = (uint)Math.Sqrt(val);
  17.             for (int i = 2; i <= maxDivider; i++)
  18.             {
  19.                 if (val % i == 0)
  20.                 {
  21.                     isPrime = false;
  22.                     break;
  23.                 }
  24.             }
  25.  
  26.             val++;
  27.  
  28.             if (isPrime)
  29.                 yield return val - 1;
  30.         }
  31.     }
  32.  
  33.     System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  34.     {
  35.         return GetEnumerator();
  36.     }
  37.  
  38. }
  39. #endregion
  40.  
  41. class ForEachExample
  42. {
  43.     static void Main()
  44.     {
  45.         //// An array of integers
  46.         //int[] numbers = { 10, 32, 3, 54, 15 };
  47.  
  48.         //foreach (int n in numbers)
  49.         //{
  50.         //    Console.WriteLine(n);
  51.         //}
  52.  
  53.  
  54.         //// An array of strings
  55.         //string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
  56.  
  57.         //foreach (string day in days)
  58.         //{
  59.         //    Console.WriteLine(day);
  60.         //}
  61.  
  62.         //endless loop
  63.         Primes primes = new Primes();
  64.  
  65.         foreach (uint prime in primes)
  66.         {
  67.             Console.WriteLine(prime);
  68.         }
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment