We previously used the break keyword in a switch statement. You also can use the break keyword in a for statement. The break keyword is used within the code of a for statement, commonly within an if statement nested inside the for statement.
The break statement transfers control immediately to the statement following the for statement. Stated another way, the break statement prematurely ends the execution of the for statement before its condition becomes false. For example, the following code will output only 5 through 7, not 5 through 10, because the loop ends prematurely when x equals a number evenly divisible by 4 (here, 8):
private void Form1 Load(object sender, EventArgs e) {
for (int num = 5; num <= 10; num++) {
if (num % 4 == 0 ) break;
Debug.WriteLine(num); }
Debug.WriteLine("This line will always print"); }
Although the break keyword is part of the C# language, I recommend you use it sparingly. Normally, the for statement has one exit point—the condition when it becomes false. However, when you use one or more break
statements, the for statement has multiple exit points. This makes your code more difficult to understand and can result in logic errors.
In the following program, the logical && (And) operator is an alternative to using the break keyword:
private void Form1_Load (object sender, EventArgs e) {
for (int num = 5; num <= 10 && num % 4 > 0; num++) Debug.WriteLine(num);
Debug.WriteLine("This line will always print"); }
Before leaving the discussion of the break keyword, one additional use of it (in conjunction with the parentheses following the for keyword being empty of all three expressions) deserves mention simply because you may encounter it. The following program is a variant of the one that outputs numbers
between 1 and 10, with the first and third expressions inside the parentheses being empty because num is initialized before the for loop and incremented inside the body of the loop. In this program, the second expression—the condition—is missing as well. Instead, the break keyword inside the if/else structure substitutes for that condition.
private void Form1_Load(object sender, EventArgs e) { int num = 1; for (;;) { if (num > 10) break; else { Debug.WriteLine(num + " "); num++; }
} }
Without the break keyword, the for loop would be infinite due to the lack of a second expression. Again, however, I do recommend against this use of the break keyword, and point it out simply because other programmers believe differently, and therefore you're likely to encounter it at some point in time.
The Continue Keyword
You also can use the continue keyword in a for statement. The continue keyword, like the break keyword, is used within the code of a for statement, commonly within an if/else structure. If the continue statement is reached, the current iteration of the loop ends, and the next iteration of the loop begins.
For example, in the following program, the user is charged $3 an item, but not charged for a "baker's dozen." In other words, every 13th item is free (the user is charged for only a dozen items, instead of 13). The program
assumes a project like the one we used in Chapter 7, in which the form contains two controls, a TextBox control named txtInput (where the user will enter the number of items) and a Button control named btnCalculate:
private void btnTest_Click(object sender, EventArgs e) {
string strItems;
int intItems, total = 0; strItems = txtInput.Text;
intItems = Int32.Parse(strItems);
for (int counter = 1; counter <= intItems; counter++) { if (counter % 13 == 0) continue; total += 3; } Debug.WriteLine
("Total for " + intItems + " items is $" + total); }
The price for 12 or 13 items is the same, $36. However, on the 14th item the user again is charged an additional $3, for a total of $39. The reason why the code charges the user no additional price for the 13th item is that the
Although the continue keyword is part of the C# language, I recommend, as I do with the break keyword, that you use it sparingly. Normally, each iteration of a for statement has one end point. However, when you use a continue statement, each iteration has multiple end points. This makes your code more difficult to understand, and can result in logic errors.
In the following program, the logical ! (Not) operator is an alternative to using the continue keyword:
private void btnTest_Click(object sender, EventArgs e) {
string strItems;
int intItems, total = 0; strItems = txtInput.Text;
intItems = Int32.Parse(strItems);
for (int counter = 1; counter <= intItems; counter++) {
if (! (counter % 13 == 0 )) total += 3;
}
Debug.WriteLine
("Total for " + intItems + " items is $" + total); }
Note You also could use the relational != (not equal) operator, changing the if statement to if (counter % 13 != 0).
Nesting
You can nest a for statement just as you can nest if statements. For example, the following program prints five rows of ten X characters:
private void Form1_Load (object sender, EventArgs e) {
for (int x = 1; x <= 5; x++) {
for (int y = 1; y <= 10; y++) Debug.Write("X");
Debug.WriteLine (""); }
}
for (int x = l; x <= 5; x++)
is the outer for loop, and the for loop
for (int y = 1; y <= 10; y++)
is the inner for loop.
With nested for loops, for each iteration of the outer for loop, the inner for loop goes through all its iterations. By analogy, in a clock, minutes are the outer loop, seconds the inner loop. For each iteration of a minute, there are 60 iterations of seconds.
In the rows and columns example, for the first iteration of the outer for loop, the inner for loop goes through all ten of its iterations, printing ten X
characters. Then, for the next iteration of the outer for loop, the inner for loop again goes through all ten of its iterations, again printing ten X characters. The same thing happens on the third, fourth, and fifth iterations of the outer for loop, resulting in five rows of ten X characters. The outer for statement represents the rows, and the inner for statement represents the columns.
The Foreach Statement
The foreach statement is similar to the for statement, but it executes the statement block for each element in a collection, instead of a specified number of times. A collection is a group of usually like objects. The syntax is shown here:
foreach ([Data Type] [variable] in [Collection] ) //code
For example, a form has a Controls collection, which is a collection of all the controls on a form. The following code displays in the Output window the name of each control in the form, which is represented by the this keyword:
private void Form1_Load(object sender, EventArgs e) {
foreach (Control ctl in this.Controls) Debug.WriteLine(ctl.Name);
}