Learn to repeat the same job again and again with for, while, do-while and foreach, using series/parallel resistance and multiplication table examples.
Why loops?
If you need to do something 100 times, you don't write the line 100 times; you write a loop. The power of computers comes from repeating without getting bored.
The for loop
If you know how many times to repeat, for is ideal. It has three parts: the start, the condition, and the step after each round.
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"{i} x 7 = {i * 7}");
}
1 x 7 = 7
2 x 7 = 14
3 x 7 = 21
4 x 7 = 28
5 x 7 = 35
The flow is like this: i starts as 1; if the condition (i <= 5) is true, the body runs; then i++ increases it by one; when the condition becomes false, the loop ends.
The while loop
When you don't know how many rounds there will be and want to continue as long as a condition holds, you use while. Example: a capacitor discharging. Let the voltage halve at every step, and let's count until it drops below 0.1 V.
double voltage = 10.0;
int steps = 0;
while (voltage >= 0.1)
{
voltage /= 2;
steps++;
}
Console.WriteLine($"After {steps} steps the voltage fell to {voltage:F4} V.");
After 7 steps the voltage fell to 0.0781 V.
Check the calculation: 10 → 5 → 2.5 → 1.25 → 0.625 → 0.3125 → 0.15625 → 0.078125. After the seventh halving it drops below 0.1.
Infinite loop: If nothing in the body changes in a way that can make the condition false, the loop never ends. If the program seems frozen, stop it in the terminal with Ctrl + C.
do-while: run at least once
do-while checks the condition at the end, so the body runs at least once. It is tailor-made for asking the user for valid input:
int number;
bool isValid;
do
{
Console.Write("Enter a number between 1 and 10: ");
isValid = int.TryParse(Console.ReadLine(), out number) && number >= 1 && number <= 10;
}
while (!isValid);
Console.WriteLine($"The number you entered: {number}");
foreach: walking through a collection
It is used to process every element of a list or array in turn. You don't have to manage a counter. (We will look at arrays in detail in the next lessons.)
double[] resistors = { 100, 220, 330 };
double series = 0;
double inverse = 0;
foreach (double r in resistors)
{
series += r;
inverse += 1 / r;
}
Console.WriteLine($"Series: {series} ohm");
Console.WriteLine($"Parallel: {1 / inverse:F2} ohm");
Series: 650 ohm
Parallel: 56.90 ohm
In a series connection, the resistances add up. In parallel, the reciprocal of the equivalent resistance is the sum of the reciprocals of the resistances: 1/R = 1/100 + 1/220 + 1/330, and the result is about 56.90 ohm.
break and continue
break ends the loop completely, while continue skips the current round and moves on to the next.
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0) continue; // skip the even numbers
if (i > 7) break; // stop after 7
Console.Write(i + " ");
}
1 3 5 7
Nested loops
for (int row = 1; row <= 3; row++)
{
for (int column = 1; column <= 3; column++)
{
Console.Write($"{row * column}\t");
}
Console.WriteLine();
}
1 2 3
2 4 6
3 6 9
Tip: Think about choosing like this: for if the number of rounds is known, while if it depends on a condition, do-while if it must run at least once, and foreach if you are going through a collection.
Try it yourself
Find the sum of the numbers from 1 to 100 with for (expected: 5050). Then add up only the ones divisible by 3. After that, write a program that prints the numbers from 1 to 20 and prints "Beep" in place of the numbers divisible by 3.
// Mini quiz
Click an option; you will see right away, with the reason, whether it is correct or not.
Mark it when you finish: your progress is saved and you earn +20 XP.
Tip: ← → keys let you move between lessons.