← Вернуться к курсу: C# from scratch

Loops: while, for, do-while and week review

Видео скоро появится

A loop repeats a block of code while a condition holds or a number of times. Thanks to loops, a four-line program can process a thousand data items. C# has four: while, do-while, for and foreach. Today we study the first three, and foreach comes next week together with collections. At the end, a review of week 3 with a five-question quiz.

while and do-while

while checks the condition before each round: if it is false from the start, the block never runs. do-while checks at the end, so the block runs at least once, which is very handy for menus and for asking for a value until it is valid. The biggest risk is the infinite loop: if nothing inside the block changes the condition, the program never ends. If it happens in the console, press Ctrl+C to stop it and check which variable was supposed to change.

csharp
int countdown = 3;
while (countdown > 0)
{
    Console.WriteLine(countdown);
    countdown--;                 // without this line: infinite loop
}
Console.WriteLine("Liftoff!");

int number;
do
{
    Console.Write("Enter a number from 1 to 10: ");
    string text = Console.ReadLine() ?? "";
    int.TryParse(text, out number);
}
while (number < 1 || number > 10);
Console.WriteLine($"You chose {number}");

for

When you know how many times to repeat, for gathers the three parts in a single line: the initialization (int i = 0), the condition (i < 5) and the step (i++). Programmers start counting from 0 by habit, because array indexes also start at 0. A very frequent bug is the off-by-one error: using <= where < was needed, and running one round too many. You can count backwards or skip by two by changing the initialization and the step, and nest one loop inside another to build tables.

csharp
for (int i = 0; i < 5; i++)
{
    Console.Write(i + " ");          // 0 1 2 3 4
}
Console.WriteLine();

for (int i = 10; i >= 0; i -= 5)
{
    Console.Write(i + " ");          // 10 5 0
}
Console.WriteLine();

// multiplication table with nested loops
for (int row = 1; row <= 3; row++)
{
    for (int col = 1; col <= 3; col++)
    {
        Console.Write($"{row * col,4}");
    }
    Console.WriteLine();
}

break and continue

Two keywords control the flow inside a loop: break ends it immediately and continue jumps to the next round without running the rest of the block. They are useful for cases like stopping the search when you already found what you wanted or ignoring data that is not valid. With nested loops, break only exits the innermost loop. Use them sparingly: a loop with many break and continue statements is hard to follow, and often a better-designed condition solves it.

csharp
// sum of the odd numbers up to 10, stopping if the sum passes 20
int sum = 0;
for (int i = 1; i <= 10; i++)
{
    if (i % 2 == 0) continue;     // skip even numbers
    sum += i;
    if (sum > 20) break;          // stop early
}
Console.WriteLine(sum);           // 25 (1+3+5+7+9)

Проверьте себя

Вопрос 1 из 6

Which loop always runs at least once?

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →