Книга: C# 2008 Programmer

for Loop

for Loop

The for loop executes a statement (or a block of statements) until a specified expression evaluates to false. The for loop has the following format:

for (statement; expression; statement(s)) {
 //---statement(s)
}

The expression inside the for loop is evaluated first, before the execution of the loop. Consider the following example:

int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int i=0; i<9; i++) {
 Console.WriteLine(nums[i].ToString());
}

Here, nums is an integer array with nine members. The initial value of i is 0 and after each iteration it increments by 1. The loop will continue as long as i is less than 9. The loop prints out the numbers from the array:

1
2
3
4
5
6
7
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).

Оглавление книги


Генерация: 0.530. Запросов К БД/Cache: 2 / 0
поделиться
Вверх Вниз