}
This code prints the strings in the words array, from index 2 through 4. The output is:
Programming
is
fun
You can also omit statements and expressions inside the
for loop, as the following example illustrates:
for (;;) {
Console.Write("*");
}
In this case, the for
loop prints out a series of *s continuously (infinite loop).
It is common to nest two or more for loops within one another. The following example prints out the times table from 1 to 10:
for (int i = 1; i <= 10; i++) {
Console.WriteLine("Times table for {0}", i);
Console.WriteLine("=================");
for (int j = 1; j <= 10; j++) {
Console.WriteLine ("{0} x {1} = {2}", i, j, i*j);
}
}
Figure 3-11 shows the output.
Figure 3-11
Here, one for
loop is nested within another for
loop. The first pass of the outer loop (represented by i
in this example) triggers the inner loop (represented by j
). The inner loop will execute to completion and then the outer loop will move to the second pass, which triggers the inner loop again. This repeats until the outer loop has finished executing.
One common use for the for loop is to iterate through a series of objects in a collection. In C# there is another looping construct that is very useful for just this purpose — the foreach statement, which iterates over each element in a collection. Take a look at an example:
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach (int i in nums) {
Console.WriteLine(i);
}
This code block prints out all the numbers in the nums array (from 1 to 9). The value of i
takes on the value of each individual member of the array during each iteration. However, you cannot change the value of i
within the loop, as the following example demonstrates:
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach (int i in nums) {
i += 4; //---error: cannot change the value of i---
Console.WriteLine(i);
}
Here is another example of the use of the foreach loop:
string[] words = { "C#", "3.0", "Programming", "is", "fun" };
foreach (string w in words) {
Console.WriteLine(w);
}
This code block prints out:
C#
3.0
Programming
is
fun
In addition to for
and foreach
statements, you can use a while
statement to execute a block of code repeatedly. The while
statement executes a code block until the specified condition is false. Here's an example:
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int i = 0;
while (i < 9) {
Console.WriteLine(nums[i++]);
}
This code iterates through all the elements (from index 0 to 8) in the nums
array and prints out each number to the console window.
The while
statement checks the condition before executing the block of code. To execute the code at least once before evaluating the condition, use the do-while
statement. It executes its code and then evaluates the condition specified by the while keyword, as the following example shows:
string reply;
do {
Console.WriteLine("Are you sure you want to quit? [y/n]");
reply = Console.ReadLine();
} while (reply != "y");
In this code, you first print the message on the console and then wait for the user to enter a string. If the string entered is not y, the loop continues. It will exit when the user enters y
.
To break out of a loop prematurely (before the exit condition is met), you can use one of the following keywords:
□ break
□ return
□ throw
□ goto
break
The break
keyword allows you to break out of a loop prematurely:
int counter = 0;
do {
Console.WriteLine(counter++);
//---exits the loop when counter is more than 100
if (counter > 100) break;
} while (true);
In this example, you increment the value of counter
in an infinite do-while
loop. To break out of the loop, you use a if
statement to check the value of counter. If the value exceeds 100, you use the break
keyword to exit the do-while
loop.
You can also use the break keyword in while
, for
, and foreach
loops.
return
The return
keyword allows you to terminate the execution of a method and return control to the calling method. When you use it within a loop, it will also exit from the loop. In the following example, the FindWord()
function searches for a specified word ("car") inside a given array. As soon as a match is found, it exits from the loop and returns control to the calling method:
class Program {
static string FindWord(string[] arr, string word) {
foreach (string w in arr) {
//--- if word is found, exit the loop and return back to the
// calling function---
if (w.StartsWith(word)) return w;
}
return string.Empty;
}
static void Main(string[] args) {
string[] words = {
"-online", "4u", "adipex", "advicer", "baccarrat", "blackjack",
"bllogspot", "booker", "byob", "car-rental-e-site",
"car-rentals-e-site", "carisoprodol", "casino", "casinos",
"chatroom", "cialis", "coolcoolhu", "coolhu",
"credit-card-debt", "credit-report-4u"
};
Console.WriteLine(FindWord(words, "car")); //---car-rental-e-site---
}
}
throw
The throw
keyword is usually used with the try-catch-finally
statements to throw an exception. However, you can also use it to exit a loop prematurely. Consider the following block of code that contains the Sums()
function to perform some addition and division on an array:
class Program {
static double Sums(int[] nums, int num) {
double sum = 0;
foreach (double n in nums) {
if (n == 0)
throw new Exception("Nums contains zero!");
sum += num / n;
}
return sum;
}
static void Main(string[] args) {
int[] nums = { 1, 2, 3, 4, 0, 6, 7, 8, 9 };
try {
Console.WriteLine(Sums(nums, 2));
Читать дальше