8

9

Here' s another example:

string[] words = { 'C#','3.0','Programming','is','fun'};

for (int j = 2; j <= 4; ++j) {

 Console.WriteLine(words[j]);

}

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).

Nested for 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.

foreach

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

while and do-while Loops

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.

Exiting from a Loop

Вы читаете C# 2008 Programmer's Reference
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату