Demonstrate the ByTwos interface 2 : Interface : Class Interface C# Source Code


Custom Search

C# Source Code » Class Interface » Interface »

 

Demonstrate the ByTwos interface 2









    

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
using System; 

public interface ISeries { 
  int getNext(); // return next number in series 
  void reset(); // restart 
  void setStart(int x); // set starting value 
}

// Use ISeries to generate a sequence of even numbers. 
class ByTwos : ISeries { 
  int start; 
  int val; 
 
  public ByTwos() { 
    start = 0; 
    val = 0; 
  }  
 
  public int getNext() { 
    val += 2; 
    return val; 
  } 
 
  public void reset() { 
    val = start; 
  } 
 
  public void setStart(int x) { 
    start = x; 
    val = start; 
  } 
} 
 
// Use ISeries to implement a series of prime numbers.  
class Primes : ISeries {  
  int start;  
  int val;  
  
  public Primes() {  
    start = 2;  
    val = 2;  
  }   
  
  public int getNext() {  
    int i, j; 
    bool isprime; 
 
    val++; 
    for(i = val; i < 1000000; i++) { 
      isprime = true; 
      for(j = 2; j < (i/j + 1); j++) { 
        if((i%j)==0) { 
          isprime = false; 
          break; 
        } 
      } 
      if(isprime) { 
        val = i; 
        break; 
      } 
    } 
    return val;        
  }  
  
  public void reset() {  
    val = start;  
  }  
  
  public void setStart(int x) {  
    start = x;  
    val = start;  
  }  
} 
 
public class SeriesDemo2 { 
  public static void Main() { 
    ByTwos twoOb = new ByTwos(); 
    Primes primeOb = new Primes(); 
    ISeries ob; 
 
    for(int i=0; i < 5; i++) { 
      ob = twoOb; 
      Console.WriteLine("Next ByTwos value is " + 
                          ob.getNext()); 
      ob = primeOb; 
      Console.WriteLine("Next prime number is " + 
                          ob.getNext()); 
    } 
  } 
}

           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Class Interface
» Interface