Arithmetic Symbols

 

The foreach Loop

The foreach loop is a new loop added specifically for the Visual Studio C# compiler. Any foreach loop that you construct can also be created with a for loop using a slightly different formulation. The foreach loop looks like this:

 Int[] intArray = new int[] {2, 4, 6, 8, 10, 12, 2, 4, 6, 2, 4, 6}; int intTotals = 0; int intNumber = 2; foreach(int intNumber in intArray) intTotals++; 

This code would produce the answer intTotals = 3.

The alternative formulation is:

 Int[] intArray = new int[] {2, 4, 6, 8, 10, 12, 2, 4, 6, 2, 4, 6}; int intTotals = 0; int intNumber = 2; for(int kk = 0; kk < intArray.Length; kk++)   if(intArray[kk] == intNumber) intTotals++; 

This code would also produce the answer intTotals = 3.

According to the Microsoft literature, a foreach loop is much faster than a for + if construct.

 


Unlocking Microsoft C# V 2.0 Programming Secrets
Unlocking Microsoft C# V 2.0 Programming Secrets (Wordware Applications Library)
ISBN: 1556220979
EAN: 2147483647
Year: 2005
Pages: 129

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net