Книга: 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
.
- The while Statement
- Разработка приложений баз данных InterBase на Borland Delphi
- Open Source Insight and Discussion
- Introduction to Microprocessors and Microcontrollers
- Chapter 6. Traversing of tables and chains
- Chapter 8. Saving and restoring large rule-sets
- Chapter 11. Iptables targets and jumps
- Chapter 5 Installing and Configuring VirtualCenter 2.0
- Chapter 16. Commercial products based on Linux, iptables and netfilter
- Appendix A. Detailed explanations of special commands
- Appendix B. Common problems and questions
- Appendix E. Other resources and links