10 полезных методов использования циклов while в C#

В C# цикл while — это оператор потока управления, который позволяет многократно выполнять блок кода, пока заданное условие истинно. Вот несколько методов, связанных с циклами while в C#:

  1. Базовый цикл while:

    while (condition)
    {
       // Code to be executed
    }
  2. Бесконечный цикл:

    while (true)
    {
       // Code to be executed indefinitely
    }
  3. Цикл со счетчиком:

    int counter = 0;
    while (counter < limit)
    {
       // Code to be executed
       counter++;
    }
  4. Цикл с пользовательским вводом:

    string input = string.Empty;
    while (input != "exit")
    {
       // Code to be executed
       Console.WriteLine("Enter 'exit' to quit:");
       input = Console.ReadLine();
    }
  5. Цикл с оператором разрыва:

    while (condition)
    {
       // Code to be executed
       if (someCondition)
       {
           break; // Exit the loop
       }
    }
  6. Цикл с оператором continue:

    while (condition)
    {
       // Code to be executed
       if (someCondition)
       {
           continue; // Skip the rest of the loop and continue with the next iteration
       }
    }
  7. Цикл с несколькими условиями:

    while (condition1 && condition2)
    {
       // Code to be executed
    }
  8. Вложенные циклы while:

    while (condition1)
    {
       while (condition2)
       {
           // Code to be executed
       }
    }
  9. Цикл по коллекции:

    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++;
    }
  10. Цикл с контрольным значением:

    string input = string.Empty;
    while (input != "quit")
    {
        // Code to be executed
        Console.WriteLine("Enter 'quit' to exit:");
        input = Console.ReadLine();
    }