Iteration (Looping) Statements

There are many situations in which you will want to do the same thing again and again, perhaps slightly changing a value each time you repeat the action. This is called iteration, or looping. Typically, you’ll iterate (or loop) over a set of items, taking the same action on each item in the collection. This is the programming equivalent of an assembly line. On an assembly line, you might take 100 car bodies and put a windshield on each one as it comes by. In an iterative program, you might work your way through a collection of text boxes on a form, retrieving the value from each in turn and using those values to update a database.

C# provides an extensive suite of iteration statements, including for and while, and also do…while and foreach loops. You can also create a loop by using the goto statement. In the remainder of this chapter, we’ll consider the use of goto, for, while, and do…while. However, we’ll postpone coverage of foreach until Chapter 10, until after we’ve introduced you to arrays.

Creating Loops with goto

We used the goto statement earlier in this chapter as an unconditional branch in a switch statement. The more common use of goto, however, is to create a loop. In fact, the goto statement is the seed from which all other looping statements have been germinated. Unfortunately, it is a semolina seed, producer of "spaghetti code” (see the "Spaghetti Code” sidebar) and endless confusion.

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.