В C# цикл while — это оператор потока управления, который позволяет многократно выполнять блок кода, пока заданное условие истинно. Вот несколько методов, связанных с циклами while в C#:
-
Базовый цикл while:
while (condition) { // Code to be executed }
-
Бесконечный цикл:
while (true) { // Code to be executed indefinitely }
-
Цикл со счетчиком:
int counter = 0; while (counter < limit) { // Code to be executed counter++; }
-
Цикл с пользовательским вводом:
string input = string.Empty; while (input != "exit") { // Code to be executed Console.WriteLine("Enter 'exit' to quit:"); input = Console.ReadLine(); }
-
Цикл с оператором разрыва:
while (condition) { // Code to be executed if (someCondition) { break; // Exit the loop } }
-
Цикл с оператором continue:
while (condition) { // Code to be executed if (someCondition) { continue; // Skip the rest of the loop and continue with the next iteration } }
-
Цикл с несколькими условиями:
while (condition1 && condition2) { // Code to be executed }
-
Вложенные циклы while:
while (condition1) { while (condition2) { // Code to be executed } }
-
Цикл по коллекции:
List<int> numbers = new List<int>(){ 1, 2, 3, 4, 5 }; int index = 0; while (index < numbers.Count) { int number = numbers[index]; // Code to be executed index++; }
-
Цикл с контрольным значением:
string input = string.Empty; while (input != "quit") { // Code to be executed Console.WriteLine("Enter 'quit' to exit:"); input = Console.ReadLine(); }