Книга: C# 2008 Programmer

while and do-while Loops

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.

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


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