- Home
- Products
- Integration
- Tutorial
- Barcode FAQ
- Purchase
- Company
for Statements in C#
for Statements Denso QR Bar Code Drawer In Visual C# Using Barcode generation for VS .NET Control to generate, create QR Code image in .NET applications. www.OnBarcode.comQuick Response Code Recognizer In Visual C#.NET Using Barcode scanner for .NET framework Control to read, scan read, scan image in VS .NET applications. www.OnBarcode.comA for statement is a loop in which some variable is initialized to a start value, and is modified each time around the loop. The loop will run for as long as some condition remains true this means a for loop does not necessarily have to involve a collection, unlike a foreach loop. Example 2-14 is a simple loop that counts to 10. QR Code ISO/IEC18004 Generation In C# Using Barcode printer for .NET framework Control to generate, create QR image in Visual Studio .NET applications. www.OnBarcode.comCode-39 Generation In C#.NET Using Barcode encoder for VS .NET Control to generate, create USS Code 39 image in Visual Studio .NET applications. www.OnBarcode.comfor (int i = 1; i <= 10; i++) { Console.WriteLine(i); } Console.WriteLine("Coming, ready or not!"); Generate UPC A In Visual C# Using Barcode creation for VS .NET Control to generate, create UPC-A image in .NET applications. www.OnBarcode.comBarcode Creator In C#.NET Using Barcode generator for VS .NET Control to generate, create Barcode image in Visual Studio .NET applications. www.OnBarcode.comThe for keyword is followed by parentheses containing three pieces. First, a variable is declared and initialized. Then the condition is specified this particular loop will Code 128A Generator In C# Using Barcode drawer for VS .NET Control to generate, create Code 128C image in Visual Studio .NET applications. www.OnBarcode.comANSI/AIM ITF 25 Maker In Visual C# Using Barcode generation for Visual Studio .NET Control to generate, create 2 of 5 Interleaved image in .NET framework applications. www.OnBarcode.comiterate for as long as the variable i is less than or equal to 10. You can use any Boolean expression here, just like in an if statement. And finally, there is a statement to be executed each time around the loop adding one to i in this case. (As you saw earlier, i++ adds one to i. We could also have written i += 1, but the usual if arbitrary convention in C-style languages is to use the ++ operator here.) QR Code Maker In .NET Framework Using Barcode encoder for Reporting Service Control to generate, create QR-Code image in Reporting Service applications. www.OnBarcode.comQR Encoder In None Using Barcode generation for Font Control to generate, create QR Code JIS X 0510 image in Font applications. www.OnBarcode.comEarlier we recommended using variable names that are long enough to be descriptive, so you might be raising an eyebrow over the use of i as a variable name. There s a convention with for loops where the iteration variable just counts up from zero short variable names such as i, j, k, x, and y are often used. It s not a universal convention, but you ll see it widely used, particularly with short loops. We re using this convention in Example 2-14 only because you will come across it sooner or later, and so we felt it was important to show it. But it s arguably not an especially good way to write clear code, so feel free to choose more meaningful names in your own code. Generating Code 128B In Objective-C Using Barcode drawer for iPhone Control to generate, create Code 128C image in iPhone applications. www.OnBarcode.comEncoding EAN 128 In None Using Barcode drawer for Office Excel Control to generate, create GTIN - 128 image in Office Excel applications. www.OnBarcode.comWe could use this construct as an alternative way to find the fastest lap time, as shown in Example 2-15. Make DataMatrix In Objective-C Using Barcode generator for iPad Control to generate, create ECC200 image in iPad applications. www.OnBarcode.comRecognize QR Code In None Using Barcode scanner for Software Control to read, scan read, scan image in Software applications. www.OnBarcode.comstring[] lines = File.ReadAllLines("LapTimes.txt"); double currentLapStartTime = 0; double fastestLapTime = 0; int fastestLapNumber = 0; for (int lapNumber = 1; lapNumber <= lines.Length; lapNumber++) { double lapEndTime = double.Parse(lines[lapNumber - 1]); double lapTime = lapEndTime - currentLapStartTime; if (fastestLapTime == 0 || lapTime < fastestLapTime) { fastestLapTime = lapTime; fastestLapNumber = lapNumber; } currentLapStartTime = lapEndTime; } Console.WriteLine("Fastest lap: " + fastestLapNumber); Console.WriteLine("Fastest lap time: " + fastestLapTime); UPCA Recognizer In Visual C#.NET Using Barcode reader for VS .NET Control to read, scan read, scan image in VS .NET applications. www.OnBarcode.comEAN128 Maker In Objective-C Using Barcode printer for iPhone Control to generate, create GS1-128 image in iPhone applications. www.OnBarcode.comThis is pretty similar to the foreach example. It s marginally shorter, but it s also a little more awkward our program is counting the laps starting from 1, but arrays in .NET start from zero, so the line that parses the value from the file has the slightly ungainly expression lines[lapNumber - 1] in it. (Incidentally, this example avoids using a short iteration variable name such as i because we re numbering the laps from 1, not 0 short iteration variable names tend to be associated with zero-based counting.) Arguably, the foreach version was clearer, even if it was ever so slightly longer. The main Print Code 39 Extended In Objective-C Using Barcode drawer for iPad Control to generate, create ANSI/AIM Code 39 image in iPad applications. www.OnBarcode.comPrint ANSI/AIM Code 39 In Visual Basic .NET Using Barcode maker for VS .NET Control to generate, create Code39 image in VS .NET applications. www.OnBarcode.comadvantage of for is that it doesn t require a collection, so it s better suited to Example 2-14 than Example 2-15. Barcode Decoder In Java Using Barcode reader for Java Control to read, scan read, scan image in Java applications. www.OnBarcode.comScan QR Code 2d Barcode In Visual Basic .NET Using Barcode recognizer for .NET Control to read, scan read, scan image in Visual Studio .NET applications. www.OnBarcode.comwhile and do Statements
C# offers a third kind of iteration statement: the while loop. This is like a simplified for loop it has only the Boolean expression that decides whether to carry on looping, and does not have the variable initialization part, or the statement to execute each time around. (Or if you prefer, a for loop is a fancy version of a while loop neither for nor foreach does anything you couldn t achieve with a while loop and a little extra code.) Example 2-16 shows an alternative approach to working through the lines of a text file based on a while loop. static void Main(string[] args) { using (StreamReader times = File.OpenText("LapTimes.txt")) { while (!times.EndOfStream) { string line = times.ReadLine(); double lapEndTime = double.Parse(line); Console.WriteLine(lapEndTime); } } } The while statement is well suited to the one-line-at-a-time approach. It doesn t require a collection; it just loops until the condition becomes false. In this example, that means we loop until the StreamReader tells us we ve reached the end of the file.# ( 11 describes the use of types such as StreamReader in detail.) The exclamation mark (!) in front of the expression means not you can put this in front of any Boolean expression to invert the result. So the loop runs for as long as we are not at the end of the stream. We could have used a for loop to implement this one-line-at-a-time loop it also iterates until its condition becomes false. The while loop happens to be a better choice here simply because in this example, we have no use for the variable initialization or loop statement offered by for. #You ll have noticed the using keyword on the line where we get hold of the StreamReader. We use this construct when it s necessary to indicate exactly when we ve finished with an object in this case we need to say when we re done with the file to avoid keeping operating system file handles open. The approach in Example 2-16 would be better than the previous examples for a particularly large file. The code can start working straight away without having to wait for the entire file to load, and it will use less memory because it doesn t build the array containing every single line it can hold just one line at a time in memory. For our example lap time file with just six lines of data, this won t make any difference, but if you were processing a file with hundreds of thousands of entries, this while-based example could provide noticeably better performance than the array-based examples. This does not mean that while is faster than for or foreach. The performance difference here is a result of the code working with the file in a different way, and has nothing to do with the loop construct. In general, it s a bad idea to focus on which language features are fastest. Performance usually depends on the way in which your code solves a problem, rather than which particular language feature you use. Note that for and while loops might never execute their contents at all. If the condition is false the first time around, they ll skip the loop entirely. This is often desirable if there s no data, you probably want to do no work. But just occasionally it can be useful to write a loop that is guaranteed to execute at least once. We can do this with a variation on the while loop, called the do while loop: do { Console.WriteLine("Waiting..."); } while (DateTime.Now.Hour < 8); The while keyword and condition come at the end, and we mark the start of the loop with the do keyword. This loop always executes at least once, testing the condition at the end of each iteration instead of the start. So this code will repeatedly show the message Waiting... until the current time is 8:00 a.m. or later. If it s already past 8:00 a.m., it ll still write out Waiting... once.
|
|