Learn/C#/5. Loops
Lesson 5 of 15
Sign in

C#, lesson 5

Loops

A loop runs a block of code again and again while a condition holds. It is how you process a hundred lines of input with ten lines of code.

The for loop

Use for when you are counting:

The header has three parts separated by semicolons: the initializer (int i = 1, runs once), the condition (i <= 5, checked before every pass) and the iterator (i++, runs after every pass). Count down with i-- or jump with i += 2. The variable i only exists inside the loop.

The while and do loops

Use while when you know when to stop but not how many passes it will take:

2 exercises to try what you just read.

Exercise 1

Times table

Press Ctrl Enter or Check to test your code.

Exercise 2

Step counter

Press Ctrl Enter or Check to test your code.

If the condition is false at the start, the body never runs. A do { ... } while (condition); loop checks at the end instead, so its body always runs at least once. That suits "ask until the answer is valid" situations.

Reading until the input runs out

Console.ReadLine() returns null when there is no more input. A neat C# idiom combines the read and the check using a type pattern:

is string line is true only when the result is an actual string (not null), and in that case it also stores it in the new variable line. The loop ends cleanly at the end of the input.

break and continue

  • break leaves the loop immediately.
  • continue skips the rest of this pass and starts the next one.

They keep loops flat instead of nesting if inside if.

Accumulators

Most loops build a result in an accumulator: a variable declared before the loop and updated inside it, such as a running total, a counter or the best value so far. Declaring it inside the loop would reset it on every pass, a classic beginner bug.

Make sure something in the loop moves you toward the exit. A loop whose condition never becomes false runs until the program is stopped for taking too long.

Further reading

  • Iteration statements (for, while, do, foreach)
  • Jump statements (break, continue)
  • Type and declaration patterns

Read one whole number n and print its times table from 1 to 10, one line each, in the form n x i = result.

Sample input:

Sample output:

A fitness tracker sends one whole number per line: the steps walked each day. A line containing 0 means "tracking stopped", and the input may also simply end. Stop at whichever comes first; the 0 itself is not a day.

Print three lines: the number of days, the total steps, and the best day. If there are no days, all three are 0.

Sample input:

Sample output:

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine($"Lap {i}");
}
int balance = 100;
int months = 0;
while (balance < 200)
{
    balance += balance / 10;   // 10% growth
    months++;
}
Console.WriteLine($"{months} months");
while (Console.ReadLine() is string line)
{
    if (string.IsNullOrWhiteSpace(line)) continue;   // skip blank lines
    Console.WriteLine($"Got: {line}");
}
for (int n = 1; n <= 100; n++)
{
    if (n % 7 != 0) continue;   // not a multiple of 7
    if (n > 30) break;          // far enough
    Console.WriteLine(n);       // 7 14 21 28
}
7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
8000
12000
5000
0
9999
Days: 3
Total: 25000
Best: 12000