← All lessons

Level 1 / C# Fundamentals / fundamental 4 of 7

Repeating work with loops

Repeat code with for, while, and foreach, and stop a loop early with break.

A loop runs the same block again and again, which is exactly what you are doing in these drills. You will write the three loops C# developers use constantly, then put if statements and running totals inside them.

Understand the idea

for: when you know the count

for (int i = 0; i < 5; i++) has three parts separated by semicolons: start the counter, keep going while this is true, and what to do after each pass. Counting from 0 with < is the C# habit because collections start at index 0.

while: until something changes

while (condition) checks first and repeats as long as the condition stays true. Something inside the loop has to move toward false, or the loop never ends.

foreach: every item in a collection

foreach (int score in scores) hands you each item in turn without a counter. Use break to leave any loop early once you have what you need.

English to C#

“Count from 0 to 4 and print i each time.”

for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
int i = 0
start the counter at 0
i < 5
keep going while this is true
i++
after each pass, add 1
{ ... }
the work repeated each pass

Rep 1 of 12

Copy it

In English

Count from 0 to 4 with a for loop and print i each time.

Type the code shown below. Watch it turn green as you go.

for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}

Waiting for you to type · 0 of 23 pieces

Ctrl+Enter checks or moves on. Tab indents. Paste is off on purpose: your hands are learning this too.

Reps

0 of 12 done

Reps unlock in order, because each one builds on the last.

How your code is checked

Drills compare what you type with known-correct C#, token by token. Spacing, line breaks, and comments do not matter; spelling, case, and punctuation do. It is not a compiler, so it accepts the listed spellings of each answer and nothing else.

Try it in a real .NET project

Print a multiplication table from 1 to 10 using a for loop inside another for loop. Then rewrite the outer loop as a while loop, and finally keep asking for input in a while loop until the user types quit.

Check your understanding

for (int i = 0; i <= 5; i++) and for (int i = 0; i < 5; i++) differ by one character. How many times does each run?

Show the explanation

The first runs six times (0 through 5) and the second runs five times (0 through 4). Off-by-one mistakes like this are the most common loop bug, which is why counting from 0 with < Length or < Count is the standard habit.

Goose School teaches Microsoft's stack. Goose Solutions is not affiliated with, endorsed by, or sponsored by Microsoft.