Repeating with loops

Run the same code many times without writing it many times.

Your C# code runs inside your browser tab. Nothing to install.

Counting with a loop

A loop runs the same block of code several times.

A for loop has three parts in its brackets: where to start, when to keep going, and what to change each time. i++ adds one to i.

The loop variable holds a different number on each pass.

Example
for (int i = 1; i <= 3; i++) {
    Console.WriteLine(i);
}

Your turn: counting

Count a little further than the example does.

Practice task

Use a loop to print the numbers from 1 to 5, one on each line.

Your answer is run and checked in the lesson. Create a free account to try it.

Building up a result

A loop is often used to build up one answer. Create a variable before the loop, change it inside the loop, and use it after the loop.

total += i is a short way to write total = total + i.

The print in the example comes after the loop has closed, so it runs once, at the end.

Example
int total = 0;
for (int i = 1; i <= 4; i++) {
    total += i;
}
Console.WriteLine(total);

Repeating while something is true

A while loop repeats for as long as its condition is true. Use it when you do not know in advance how many passes are needed.

Something inside the loop must change so that the condition becomes false. If nothing does, the loop never ends.

The example halves a number until it drops below 10.

Example
int n = 80;
while (n >= 10) {
    Console.WriteLine(n);
    n = n / 2;
}

Your turn: a total

Combine a loop with a running total.

Practice task

Use a loop to add the numbers from 1 to 10, then print the total once.

Your answer is run and checked in the lesson. Create a free account to try it.